<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222" media="(prefers-color-scheme: light)">
<meta name="theme-color" content="#222" media="(prefers-color-scheme: dark)"><meta name="generator" content="Hexo 7.3.0">

  <link rel="apple-touch-icon" sizes="180x180" href="/img/iconfont.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/img/iconfont.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/img/iconfont.png">
  <link rel="mask-icon" href="/img/iconfont.png" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/7.0.0/css/all.min.css" integrity="sha256-VHqXKFhhMxcpubYf9xiWdCiojEbY9NexQ4jh8AxbvcM=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"wang-weijun.github.io","root":"/","images":"/images","scheme":"Pisces","darkmode":true,"version":"8.26.0","exturl":false,"sidebar":{"position":"left","width_expanded":320,"width_dual_column":240,"display":"post","padding":18,"offset":12},"hljswrap":true,"codeblock":{"theme":{"light":"default","dark":"stackoverflow-dark"},"prism":{"light":"prism","dark":"prism-dark"},"copy_button":{"enable":false,"style":null},"fold":{"enable":false,"height":500},"language":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"duration":200,"transition":{"menu_item":"fadeInDown","post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.json","localsearch":{"enable":true,"top_n_per_article":1,"unescape":false,"preload":false}}</script><script src="/js/config.js" defer></script>

    <meta name="description" content="通过 LangChain4j 将大模型集成到Java程序。">
<meta property="og:type" content="article">
<meta property="og:title" content="硅谷小智">
<meta property="og:url" content="http://wang-weijun.github.io/2025/04/22/%E7%A1%85%E8%B0%B7%E5%B0%8F%E6%99%BA/index.html">
<meta property="og:site_name" content="Phils的杂货铺">
<meta property="og:description" content="通过 LangChain4j 将大模型集成到Java程序。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://wang-weijun.github.io/images/202504252303548.png">
<meta property="article:published_time" content="2025-04-22T15:02:21.000Z">
<meta property="article:modified_time" content="2025-11-21T08:58:26.679Z">
<meta property="article:author" content="Phils">
<meta property="article:tag" content="Java">
<meta property="article:tag" content="LangChain4j">
<meta property="article:tag" content="RAG">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://wang-weijun.github.io/images/202504252303548.png">


<link rel="canonical" href="http://wang-weijun.github.io/2025/04/22/%E7%A1%85%E8%B0%B7%E5%B0%8F%E6%99%BA/">


<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"http://wang-weijun.github.io/2025/04/22/%E7%A1%85%E8%B0%B7%E5%B0%8F%E6%99%BA/","path":"2025/04/22/硅谷小智/","title":"硅谷小智"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>硅谷小智 | Phils的杂货铺</title>
  








  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous" defer></script>
<script src="/js/utils.js" defer></script><script src="/js/motion.js" defer></script><script src="/js/sidebar.js" defer></script><script src="/js/next-boot.js" defer></script>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/hexo-generator-searchdb/1.5.0/search.js" integrity="sha256-xFC6PJ82SL9b3WkGjFavNiA9gm5z6UBxWPiu4CYjptg=" crossorigin="anonymous" defer></script>
<script src="/js/third-party/search/local-search.js" defer></script>







  





  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <div class="column">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">Phils的杂货铺</p>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger" aria-label="搜索" role="button">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-about"><a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
      <div class="search-header">
        <span class="search-icon">
          <i class="fa fa-search"></i>
        </span>
        <div class="search-input-container">
          <input autocomplete="off" autocapitalize="off" maxlength="80"
                placeholder="搜索..." spellcheck="false"
                type="search" class="search-input">
        </div>
        <span class="popup-btn-close" role="button">
          <i class="fa fa-times-circle"></i>
        </span>
      </div>
      <div class="search-result-container">
        <div class="search-result-icon">
          <i class="fa fa-spinner fa-pulse fa-5x"></i>
        </div>
      </div>
    </div>
  </div>

</header>
        
  
  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E7%A1%85%E8%B0%B7%E5%B0%8F%E6%99%BA%EF%BC%88%E5%8C%BB%E7%96%97%E7%89%88%EF%BC%89"><span class="nav-number">1.</span> <span class="nav-text">硅谷小智（医疗版）</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%B8%80%E3%80%81LangChain4j%E5%85%A5%E9%97%A8"><span class="nav-number">1.1.</span> <span class="nav-text">一、LangChain4j入门</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1%E3%80%81%E7%AE%80%E4%BB%8B"><span class="nav-number">1.1.1.</span> <span class="nav-text">1、简介</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-1%E3%80%81%E5%8E%86%E5%8F%B2%E8%83%8C%E6%99%AF"><span class="nav-number">1.1.1.1.</span> <span class="nav-text">1.1、历史背景</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#1-2%E3%80%81%E4%B8%BB%E8%A6%81%E5%8A%9F%E8%83%BD"><span class="nav-number">1.1.1.2.</span> <span class="nav-text">1.2、主要功能</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#1-3%E3%80%81%E5%BA%94%E7%94%A8%E7%A4%BA%E4%BE%8B"><span class="nav-number">1.1.1.3.</span> <span class="nav-text">1.3、应用示例</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2%E3%80%81%E5%88%9B%E5%BB%BASpringBoot%E9%A1%B9%E7%9B%AE"><span class="nav-number">1.1.2.</span> <span class="nav-text">2、创建SpringBoot项目</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#2-1%E3%80%81%E5%88%9B%E5%BB%BA%E4%B8%80%E4%B8%AAMaven%E9%A1%B9%E7%9B%AE"><span class="nav-number">1.1.2.1.</span> <span class="nav-text">2.1、创建一个Maven项目</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-2%E3%80%81%E6%B7%BB%E5%8A%A0SpringBoot%E7%9B%B8%E5%85%B3%E4%BE%9D%E8%B5%96"><span class="nav-number">1.1.2.2.</span> <span class="nav-text">2.2、添加SpringBoot相关依赖</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-3%E3%80%81%E5%88%9B%E5%BB%BA%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6"><span class="nav-number">1.1.2.3.</span> <span class="nav-text">2.3、创建配置文件</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-4%E3%80%81%E5%88%9B%E5%BB%BA%E5%90%AF%E5%8A%A8%E7%B1%BB"><span class="nav-number">1.1.2.4.</span> <span class="nav-text">2.4、创建启动类</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-5%E3%80%81%E5%90%AF%E5%8A%A8%E5%90%AF%E5%8A%A8%E7%B1%BB"><span class="nav-number">1.1.2.5.</span> <span class="nav-text">2.5、启动启动类</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3%E3%80%81%E6%8E%A5%E5%85%A5%E5%A4%A7%E6%A8%A1%E5%9E%8B"><span class="nav-number">1.1.3.</span> <span class="nav-text">3、接入大模型</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#3-1%E3%80%81LangChain4j-%E5%BA%93%E7%BB%93%E6%9E%84"><span class="nav-number">1.1.3.1.</span> <span class="nav-text">3.1、LangChain4j 库结构</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-2%E3%80%81%E6%B7%BB%E5%8A%A0LangChain4j%E7%9B%B8%E5%85%B3%E4%BE%9D%E8%B5%96"><span class="nav-number">1.1.3.2.</span> <span class="nav-text">3.2、添加LangChain4j相关依赖</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-3%E3%80%81%E5%88%9B%E5%BB%BA%E6%B5%8B%E8%AF%95%E7%94%A8%E4%BE%8B"><span class="nav-number">1.1.3.3.</span> <span class="nav-text">3.3、创建测试用例</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4%E3%80%81SpringBoot%E6%95%B4%E5%90%88"><span class="nav-number">1.1.4.</span> <span class="nav-text">4、SpringBoot整合</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#4-1%E3%80%81%E6%9B%BF%E6%8D%A2%E4%BE%9D%E8%B5%96"><span class="nav-number">1.1.4.1.</span> <span class="nav-text">4.1、替换依赖</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-2%E3%80%81%E5%9C%A8application-yml%E4%B8%AD%E9%85%8D%E7%BD%AE%E6%A8%A1%E5%9E%8B%E5%8F%82%E6%95%B0"><span class="nav-number">1.1.4.2.</span> <span class="nav-text">4.2、在application.yml中配置模型参数</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-3%E3%80%81%E5%88%9B%E5%BB%BA%E6%B5%8B%E8%AF%95%E7%94%A8%E4%BE%8B"><span class="nav-number">1.1.4.3.</span> <span class="nav-text">4.3、创建测试用例</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BA%8C%E3%80%81%E6%8E%A5%E5%85%A5%E5%85%B6%E4%BB%96%E5%A4%A7%E6%A8%A1%E5%9E%8B"><span class="nav-number">1.2.</span> <span class="nav-text">二、接入其他大模型</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1%E3%80%81%E9%83%BD%E6%9C%89%E5%93%AA%E4%BA%9B%E5%A4%A7%E6%A8%A1%E5%9E%8B"><span class="nav-number">1.2.1.</span> <span class="nav-text">1、都有哪些大模型</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2%E3%80%81%E6%8E%A5%E5%85%A5DeepSeek"><span class="nav-number">1.2.2.</span> <span class="nav-text">2、接入DeepSeek</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-1%E3%80%81%E8%8E%B7%E5%8F%96%E5%BC%80%E5%8F%91%E5%8F%82%E6%95%B0"><span class="nav-number">1.2.2.1.</span> <span class="nav-text">1.1、获取开发参数</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#1-2%E3%80%81%E9%85%8D%E7%BD%AE%E5%BC%80%E5%8F%91%E5%8F%82%E6%95%B0"><span class="nav-number">1.2.2.2.</span> <span class="nav-text">1.2、配置开发参数</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#1-3%E3%80%81%E9%85%8D%E7%BD%AE%E6%A8%A1%E5%9E%8B%E5%8F%82%E6%95%B0"><span class="nav-number">1.2.2.3.</span> <span class="nav-text">1.3、配置模型参数</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#1-4%E3%80%81%E6%B5%8B%E8%AF%95"><span class="nav-number">1.2.2.4.</span> <span class="nav-text">1.4、测试</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3%E3%80%81ollama%E6%9C%AC%E5%9C%B0%E9%83%A8%E7%BD%B2"><span class="nav-number">1.2.3.</span> <span class="nav-text">3、ollama本地部署</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#3-1%E3%80%81%E4%B8%BA%E4%BB%80%E4%B9%88%E8%A6%81%E6%9C%AC%E5%9C%B0%E9%83%A8%E7%BD%B2"><span class="nav-number">1.2.3.1.</span> <span class="nav-text">3.1、为什么要本地部署</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-2%E3%80%81%E5%9C%A8ollama%E4%B8%8A%E9%83%A8%E7%BD%B2DeepSeek"><span class="nav-number">1.2.3.2.</span> <span class="nav-text">3.2、在ollama上部署DeepSeek</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-3%E3%80%81%E5%B8%B8%E7%94%A8%E5%91%BD%E4%BB%A4"><span class="nav-number">1.2.3.3.</span> <span class="nav-text">3.3、常用命令</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-4%E3%80%81%E5%BC%95%E5%85%A5%E4%BE%9D%E8%B5%96"><span class="nav-number">1.2.3.4.</span> <span class="nav-text">3.4、引入依赖</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-5%E3%80%81%E9%85%8D%E7%BD%AE%E6%A8%A1%E5%9E%8B%E5%8F%82%E6%95%B0"><span class="nav-number">1.2.3.5.</span> <span class="nav-text">3.5、配置模型参数</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-6%E3%80%81%E5%88%9B%E5%BB%BA%E6%B5%8B%E8%AF%95%E7%94%A8%E4%BE%8B"><span class="nav-number">1.2.3.6.</span> <span class="nav-text">3.6、创建测试用例</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4%E3%80%81%E6%8E%A5%E5%85%A5%E9%98%BF%E9%87%8C%E7%99%BE%E7%82%BC%E5%B9%B3%E5%8F%B0"><span class="nav-number">1.2.4.</span> <span class="nav-text">4、接入阿里百炼平台</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#4-1%E3%80%81%E4%BB%80%E4%B9%88%E6%98%AF%E9%98%BF%E9%87%8C%E7%99%BE%E7%82%BC"><span class="nav-number">1.2.4.1.</span> <span class="nav-text">4.1、什么是阿里百炼</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-2%E3%80%81%E7%94%B3%E8%AF%B7%E5%85%8D%E8%B4%B9%E4%BD%93%E9%AA%8C"><span class="nav-number">1.2.4.2.</span> <span class="nav-text">4.2、申请免费体验</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-3%E3%80%81%E6%B7%BB%E5%8A%A0%E4%BE%9D%E8%B5%96"><span class="nav-number">1.2.4.3.</span> <span class="nav-text">4.3、添加依赖</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-4%E3%80%81%E9%85%8D%E7%BD%AE%E6%A8%A1%E5%9E%8B%E5%8F%82%E6%95%B0"><span class="nav-number">1.2.4.4.</span> <span class="nav-text">4.4、配置模型参数</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-5%E3%80%81%E6%B5%8B%E8%AF%95%E9%80%9A%E4%B9%89%E5%8D%83%E9%97%AE"><span class="nav-number">1.2.4.5.</span> <span class="nav-text">4.5、测试通义千问</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-6%E3%80%81%E6%B5%8B%E8%AF%95%E9%80%9A%E4%B9%89%E4%B8%87%E8%B1%A1"><span class="nav-number">1.2.4.6.</span> <span class="nav-text">4.6、测试通义万象</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%B8%89%E3%80%81%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD%E6%9C%8D%E5%8A%A1-AIService"><span class="nav-number">1.3.</span> <span class="nav-text">三、人工智能服务 AIService</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1%E3%80%81%E4%BB%80%E4%B9%88%E6%98%AFAIService"><span class="nav-number">1.3.1.</span> <span class="nav-text">1、什么是AIService</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-1%E3%80%81%E9%93%BE-Chain%EF%BC%88%E6%97%A7%E7%89%88%EF%BC%89"><span class="nav-number">1.3.1.1.</span> <span class="nav-text">1.1、链 Chain（旧版）</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#1-2%E3%80%81%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD%E6%9C%8D%E5%8A%A1-AIService"><span class="nav-number">1.3.1.2.</span> <span class="nav-text">1.2、人工智能服务 AIService</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2%E3%80%81%E5%88%9B%E5%BB%BAAIService"><span class="nav-number">1.3.2.</span> <span class="nav-text">2、创建AIService</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#2-1%E3%80%81%E5%BC%95%E5%85%A5%E4%BE%9D%E8%B5%96"><span class="nav-number">1.3.2.1.</span> <span class="nav-text">2.1、引入依赖</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-2%E3%80%81%E5%88%9B%E5%BB%BA%E6%8E%A5%E5%8F%A3"><span class="nav-number">1.3.2.2.</span> <span class="nav-text">2.2、创建接口</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-3%E3%80%81%E6%B5%8B%E8%AF%95%E7%94%A8%E4%BE%8B"><span class="nav-number">1.3.2.3.</span> <span class="nav-text">2.3、测试用例</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-4%E3%80%81-AiService"><span class="nav-number">1.3.2.4.</span> <span class="nav-text">2.4、@AiService</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-5%E3%80%81%E5%B7%A5%E4%BD%9C%E5%8E%9F%E7%90%86"><span class="nav-number">1.3.2.5.</span> <span class="nav-text">2.5、工作原理</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%9B%9B%E3%80%81%E8%81%8A%E5%A4%A9%E8%AE%B0%E5%BF%86-Chat-memory"><span class="nav-number">1.4.</span> <span class="nav-text">四、聊天记忆 Chat memory</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1%E3%80%81%E6%B5%8B%E8%AF%95%E5%AF%B9%E8%AF%9D%E6%98%AF%E5%90%A6%E6%9C%89%E8%AE%B0%E5%BF%86"><span class="nav-number">1.4.1.</span> <span class="nav-text">1、测试对话是否有记忆</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2%E3%80%81%E8%81%8A%E5%A4%A9%E8%AE%B0%E5%BF%86%E7%9A%84%E7%AE%80%E5%8D%95%E5%AE%9E%E7%8E%B0"><span class="nav-number">1.4.2.</span> <span class="nav-text">2、聊天记忆的简单实现</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3%E3%80%81%E4%BD%BF%E7%94%A8ChatMemory%E5%AE%9E%E7%8E%B0%E8%81%8A%E5%A4%A9%E8%AE%B0%E5%BF%86"><span class="nav-number">1.4.3.</span> <span class="nav-text">3、使用ChatMemory实现聊天记忆</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4%E3%80%81%E4%BD%BF%E7%94%A8AIService%E5%AE%9E%E7%8E%B0%E8%81%8A%E5%A4%A9%E8%AE%B0%E5%BF%86"><span class="nav-number">1.4.4.</span> <span class="nav-text">4、使用AIService实现聊天记忆</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#4-1%E3%80%81%E5%88%9B%E5%BB%BA%E8%AE%B0%E5%BF%86%E5%AF%B9%E8%AF%9D%E6%99%BA%E8%83%BD%E4%BD%93"><span class="nav-number">1.4.4.1.</span> <span class="nav-text">4.1、创建记忆对话智能体</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-2%E3%80%81%E9%85%8D%E7%BD%AEChatMemory"><span class="nav-number">1.4.4.2.</span> <span class="nav-text">4.2、配置ChatMemory</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-3%E3%80%81%E6%B5%8B%E8%AF%95"><span class="nav-number">1.4.4.3.</span> <span class="nav-text">4.3、测试</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5%E3%80%81%E9%9A%94%E7%A6%BB%E8%81%8A%E5%A4%A9%E8%AE%B0%E5%BF%86"><span class="nav-number">1.4.5.</span> <span class="nav-text">5、隔离聊天记忆</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#5-1%E3%80%81%E5%88%9B%E5%BB%BA%E8%AE%B0%E5%BF%86%E9%9A%94%E7%A6%BB%E5%AF%B9%E8%AF%9D%E6%99%BA%E8%83%BD%E4%BD%93"><span class="nav-number">1.4.5.1.</span> <span class="nav-text">5.1、创建记忆隔离对话智能体</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#5-2%E3%80%81%E9%85%8D%E7%BD%AEChatMemoryProvider"><span class="nav-number">1.4.5.2.</span> <span class="nav-text">5.2、配置ChatMemoryProvider</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#5-3%E3%80%81%E6%B5%8B%E8%AF%95%E5%AF%B9%E8%AF%9D%E5%8A%A9%E6%89%8B"><span class="nav-number">1.4.5.3.</span> <span class="nav-text">5.3、测试对话助手</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BA%94%E3%80%81%E6%8C%81%E4%B9%85%E5%8C%96%E8%81%8A%E5%A4%A9%E8%AE%B0%E5%BF%86-Persistence"><span class="nav-number">1.5.</span> <span class="nav-text">五、持久化聊天记忆 Persistence</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1%E3%80%81%E5%AD%98%E5%82%A8%E4%BB%8B%E8%B4%A8%E7%9A%84%E9%80%89%E6%8B%A9"><span class="nav-number">1.5.1.</span> <span class="nav-text">1、存储介质的选择</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2%E3%80%81MongoDB"><span class="nav-number">1.5.2.</span> <span class="nav-text">2、MongoDB</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#2-1%E3%80%81%E7%AE%80%E4%BB%8B"><span class="nav-number">1.5.2.1.</span> <span class="nav-text">2.1、简介</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-2%E3%80%81%E5%AE%89%E8%A3%85MongoDB"><span class="nav-number">1.5.2.2.</span> <span class="nav-text">2.2、安装MongoDB</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-3%E3%80%81%E4%BD%BF%E7%94%A8mongosh"><span class="nav-number">1.5.2.3.</span> <span class="nav-text">2.3、使用mongosh</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-4%E3%80%81%E4%BD%BF%E7%94%A8mongodb-compass"><span class="nav-number">1.5.2.4.</span> <span class="nav-text">2.4、使用mongodb-compass</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-5%E3%80%81%E6%95%B4%E5%90%88SpringBoot"><span class="nav-number">1.5.2.5.</span> <span class="nav-text">2.5、整合SpringBoot</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-6%E3%80%81CRUD%E6%B5%8B%E8%AF%95"><span class="nav-number">1.5.2.6.</span> <span class="nav-text">2.6、CRUD测试</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3%E3%80%81%E6%8C%81%E4%B9%85%E5%8C%96%E8%81%8A%E5%A4%A9"><span class="nav-number">1.5.3.</span> <span class="nav-text">3、持久化聊天</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#3-1%E3%80%81%E4%BC%98%E5%8C%96%E5%AE%9E%E4%BD%93%E7%B1%BB"><span class="nav-number">1.5.3.1.</span> <span class="nav-text">3.1、优化实体类</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-2%E3%80%81%E5%88%9B%E5%BB%BA%E6%8C%81%E4%B9%85%E5%8C%96%E7%B1%BB"><span class="nav-number">1.5.3.2.</span> <span class="nav-text">3.2、创建持久化类</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4%E3%80%81%E6%B5%8B%E8%AF%95"><span class="nav-number">1.5.4.</span> <span class="nav-text">4、测试</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%85%AD%E3%80%81%E6%8F%90%E7%A4%BA%E8%AF%8D-Prompt"><span class="nav-number">1.6.</span> <span class="nav-text">六、提示词 Prompt</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1%E3%80%81%E7%B3%BB%E7%BB%9F%E6%8F%90%E7%A4%BA%E8%AF%8D"><span class="nav-number">1.6.1.</span> <span class="nav-text">1、系统提示词</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-1%E3%80%81%E9%85%8D%E7%BD%AE-SystemMessage"><span class="nav-number">1.6.1.1.</span> <span class="nav-text">1.1、配置@SystemMessage</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#1-2%E3%80%81%E6%B5%8B%E8%AF%95"><span class="nav-number">1.6.1.2.</span> <span class="nav-text">1.2、测试</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#1-3%E3%80%81%E4%BB%8E%E8%B5%84%E6%BA%90%E4%B8%AD%E5%8A%A0%E8%BD%BD%E6%8F%90%E7%A4%BA%E6%A8%A1%E6%9D%BF"><span class="nav-number">1.6.1.3.</span> <span class="nav-text">1.3、从资源中加载提示模板</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2%E3%80%81%E7%94%A8%E6%88%B7%E6%8F%90%E7%A4%BA%E8%AF%8D%E6%A8%A1%E6%9D%BF"><span class="nav-number">1.6.2.</span> <span class="nav-text">2、用户提示词模板</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#2-1%E3%80%81%E9%85%8D%E7%BD%AE-UserMessage"><span class="nav-number">1.6.2.1.</span> <span class="nav-text">2.1、配置@UserMessage</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-2%E3%80%81%E6%B5%8B%E8%AF%95"><span class="nav-number">1.6.2.2.</span> <span class="nav-text">2.2、测试</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3%E3%80%81%E6%8C%87%E5%AE%9A%E5%8F%82%E6%95%B0%E5%90%8D%E7%A7%B0"><span class="nav-number">1.6.3.</span> <span class="nav-text">3、指定参数名称</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#3-1%E3%80%81%E9%85%8D%E7%BD%AE-V"><span class="nav-number">1.6.3.1.</span> <span class="nav-text">3.1、配置@V</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-2%E3%80%81%E5%A4%9A%E4%B8%AA%E5%8F%82%E6%95%B0%E7%9A%84%E6%83%85%E5%86%B5"><span class="nav-number">1.6.3.2.</span> <span class="nav-text">3.2、多个参数的情况</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-3%E3%80%81-SystemMessage%E5%92%8C-V"><span class="nav-number">1.6.3.3.</span> <span class="nav-text">3.3、@SystemMessage和@V</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%B8%83%E3%80%81%E9%A1%B9%E7%9B%AE%E5%AE%9E%E6%88%98-%E5%88%9B%E5%BB%BA%E7%A1%85%E8%B0%B7%E5%B0%8F%E6%99%BA"><span class="nav-number">1.7.</span> <span class="nav-text">七、项目实战-创建硅谷小智</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1%E3%80%81%E5%88%9B%E5%BB%BA%E7%A1%85%E8%B0%B7%E5%B0%8F%E6%99%BA"><span class="nav-number">1.7.1.</span> <span class="nav-text">1、创建硅谷小智</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2%E3%80%81%E6%8F%90%E7%A4%BA%E8%AF%8D%E6%A8%A1%E6%9D%BF"><span class="nav-number">1.7.2.</span> <span class="nav-text">2、提示词模板</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3%E3%80%81%E9%85%8D%E7%BD%AE%E5%B0%8F%E6%99%BA%E5%8A%A9%E6%89%8B"><span class="nav-number">1.7.3.</span> <span class="nav-text">3、配置小智助手</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4%E3%80%81%E5%B0%81%E8%A3%85%E5%AF%B9%E8%AF%9D%E5%AF%B9%E8%B1%A1"><span class="nav-number">1.7.4.</span> <span class="nav-text">4、封装对话对象</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5%E3%80%81%E6%B7%BB%E5%8A%A0Controller%E6%96%B9%E6%B3%95"><span class="nav-number">1.7.5.</span> <span class="nav-text">5、添加Controller方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#6%E3%80%81%E5%BE%85%E4%BC%98%E5%8C%96"><span class="nav-number">1.7.6.</span> <span class="nav-text">6、待优化</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%85%AB%E3%80%81-Function-Calling-%E5%87%BD%E6%95%B0%E8%B0%83%E7%94%A8"><span class="nav-number">1.8.</span> <span class="nav-text">八、 Function Calling 函数调用</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1%E3%80%81%E5%85%A5%E9%97%A8%E6%A1%88%E4%BE%8B"><span class="nav-number">1.8.1.</span> <span class="nav-text">1、入门案例</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-1%E3%80%81%E5%88%9B%E5%BB%BA%E5%B7%A5%E5%85%B7%E7%B1%BB"><span class="nav-number">1.8.1.1.</span> <span class="nav-text">1.1、创建工具类</span></a></li></ol></li></ol></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Phils"
      src="/img/profile.png">
  <p class="site-author-name" itemprop="name">Phils</p>
  <div class="site-description" itemprop="description">个人博客，IT，技术分享</div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">40</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">15</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">40</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author animated">
      <span class="links-of-author-item">
        <a href="https://github.com/wang-weijun" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;wang-weijun" rel="noopener me" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:1191206969@qq.com" title="E-Mail → mailto:1191206969@qq.com" rel="noopener me" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>

        </div>
      </div>
    </div>

    
  </aside>


    </div>

    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://wang-weijun.github.io/2025/04/22/%E7%A1%85%E8%B0%B7%E5%B0%8F%E6%99%BA/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/img/profile.png">
      <meta itemprop="name" content="Phils">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Phils的杂货铺">
      <meta itemprop="description" content="个人博客，IT，技术分享">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="硅谷小智 | Phils的杂货铺">
      <meta itemprop="description" content="通过 LangChain4j 将大模型集成到Java程序。">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          硅谷小智
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2025-04-22 23:02:21" itemprop="dateCreated datePublished" datetime="2025-04-22T23:02:21+08:00">2025-04-22</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">更新于</span>
      <time title="修改时间：2025-11-21 16:58:26" itemprop="dateModified" datetime="2025-11-21T16:58:26+08:00">2025-11-21</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E9%A1%B9%E7%9B%AE/" itemprop="url" rel="index"><span itemprop="name">项目</span></a>
        </span>
    </span>

  
</div>

            <div class="post-description">通过 LangChain4j 将大模型集成到Java程序。</div>
        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody"><h1 id="硅谷小智（医疗版）"><a href="#硅谷小智（医疗版）" class="headerlink" title="硅谷小智（医疗版）"></a>硅谷小智（医疗版）</h1><h2 id="一、LangChain4j入门"><a href="#一、LangChain4j入门" class="headerlink" title="一、LangChain4j入门"></a>一、LangChain4j入门</h2><h3 id="1、简介"><a href="#1、简介" class="headerlink" title="1、简介"></a>1、简介</h3><p><code>LangChain4j </code>的目标是简化将大模型（LLM - Large Language Model）集成到 Java 应用程序中的过程。</p>
<h4 id="1-1、历史背景"><a href="#1-1、历史背景" class="headerlink" title="1.1、历史背景"></a>1.1、历史背景</h4><p>2022年11月30日OpenAI发布了Chat GPT (GPT-3.5)<br>早在2022年10月，Harrison Chase发布了基于Python的LangChain。<br>随后同时包含了Python版和JavaScript (LangChain.js)版的LangChain也发布了。<br>2023年11月，Quarkus 发布了LangChain4j 的0.1版本，2025年2月发布了1.0-Beta1 版本，4月发布了1.0-Beta3版本<br>官网：<a target="_blank" rel="noopener" href="https://docs.langchain4j.dev/">LangChain4j</a></p>
<h4 id="1-2、主要功能"><a href="#1-2、主要功能" class="headerlink" title="1.2、主要功能"></a>1.2、主要功能</h4><p><strong>与大型语言模型和向量数据库的便捷交互</strong><br>通过统一的应用程序编程接口(API)，可以轻松访问所有主要的商业和开源大型语言模型以及向量数据库，使你能够构建聊天机器人、智能助手等应用。<br><strong>专为 Java 打造</strong><br>借助Spring Boot集成，能够将大模型集成到 Java 应用程序中。大型语言模型与 Java 之间实现了双向集成：你可以从Java中调用大型语言模型，同时也允许大型语言模型反过来调用你的Java代码<br><strong>智能代理、工具、检索增强生成（RAG）</strong><br>为常见的大语言模型操作提供了广泛的工具，涵盖从底层的提示词模板创建、聊天记忆管理和输出解析，到智能代理和检索增强生成等高级模式。</p>
<h4 id="1-3、应用示例"><a href="#1-3、应用示例" class="headerlink" title="1.3、应用示例"></a>1.3、应用示例</h4><ol>
<li>你想要实现一个自定义的由人工智能驱动的聊天机器人，它可以访问你的数据，并按照你期望的方式运行：<ul>
<li>客户支持聊天机器人，它可以：<ul>
<li>礼貌地回答客户问题</li>
</ul>
</li>
<li>处理&#x2F;更改&#x2F;取消订单</li>
<li>教育助手，它可以：<ul>
<li>教授各种学科</li>
</ul>
</li>
<li>解释不清楚的部分<ul>
<li>评估用户的理解&#x2F;知识水平</li>
</ul>
</li>
</ul>
</li>
<li>你想要处理大量的非结构化数据（文件、网页等），并从中提取结构化信息。例如：<ul>
<li>从客户评价和支持聊天记录中提取有效评价</li>
<li>从竞争对手的网站上提取有趣的信息</li>
<li>从求职者的简历中提取有效信息</li>
</ul>
</li>
<li>你想要生成信息，例如：<ul>
<li>为你的每个客户量身定制的电子邮件</li>
<li>为你的应用程序&#x2F;网站生成内容：<ul>
<li>博客文章</li>
<li>故事</li>
</ul>
</li>
</ul>
</li>
<li>你想要转换信息，例如：<ul>
<li>总结</li>
<li>校对和改写</li>
<li>翻译</li>
</ul>
</li>
</ol>
<h3 id="2、创建SpringBoot项目"><a href="#2、创建SpringBoot项目" class="headerlink" title="2、创建SpringBoot项目"></a>2、创建SpringBoot项目</h3><h4 id="2-1、创建一个Maven项目"><a href="#2-1、创建一个Maven项目" class="headerlink" title="2.1、创建一个Maven项目"></a>2.1、创建一个Maven项目</h4><p>名称：java-ai-langchain4j</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">groupId</span>&gt;</span>com.wwj<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>java-ai-langchain4j<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>1.0-SNAPSHOT<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h4 id="2-2、添加SpringBoot相关依赖"><a href="#2-2、添加SpringBoot相关依赖" class="headerlink" title="2.2、添加SpringBoot相关依赖"></a>2.2、添加SpringBoot相关依赖</h4><p>pom.xml 配置如下：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">properties</span>&gt;</span></span><br><span class="line">       <span class="tag">&lt;<span class="name">maven.compiler.source</span>&gt;</span>17<span class="tag">&lt;/<span class="name">maven.compiler.source</span>&gt;</span></span><br><span class="line">       <span class="tag">&lt;<span class="name">maven.compiler.target</span>&gt;</span>17<span class="tag">&lt;/<span class="name">maven.compiler.target</span>&gt;</span></span><br><span class="line">       <span class="tag">&lt;<span class="name">project.build.sourceEncoding</span>&gt;</span>UTF-8<span class="tag">&lt;/<span class="name">project.build.sourceEncoding</span>&gt;</span></span><br><span class="line">       <span class="tag">&lt;<span class="name">spring-boot.version</span>&gt;</span>3.2.6<span class="tag">&lt;/<span class="name">spring-boot.version</span>&gt;</span></span><br><span class="line">       <span class="tag">&lt;<span class="name">knife4j.version</span>&gt;</span>4.3.0<span class="tag">&lt;/<span class="name">knife4j.version</span>&gt;</span></span><br><span class="line">       <span class="tag">&lt;<span class="name">langchain4j.version</span>&gt;</span>1.0.0-beta3<span class="tag">&lt;/<span class="name">langchain4j.version</span>&gt;</span></span><br><span class="line">       <span class="tag">&lt;<span class="name">mybatis-plus.version</span>&gt;</span>3.5.11<span class="tag">&lt;/<span class="name">mybatis-plus.version</span>&gt;</span></span><br><span class="line">   <span class="tag">&lt;/<span class="name">properties</span>&gt;</span></span><br><span class="line">   <span class="tag">&lt;<span class="name">dependencies</span>&gt;</span></span><br><span class="line">       <span class="comment">&lt;!-- web应用程序核心依赖 --&gt;</span></span><br><span class="line">       <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">           <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">           <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-web<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">       <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">       <span class="comment">&lt;!-- 编写和运行测试用例 --&gt;</span></span><br><span class="line">       <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">           <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">           <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-test<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">           <span class="tag">&lt;<span class="name">scope</span>&gt;</span>test<span class="tag">&lt;/<span class="name">scope</span>&gt;</span></span><br><span class="line">       <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">       <span class="comment">&lt;!-- 前后端分离中的后端接口测试工具 --&gt;</span></span><br><span class="line">       <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">           <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>com.github.xiaoymin<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">           <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>knife4j-openapi3-jakarta-spring-boot-starter<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">           <span class="tag">&lt;<span class="name">version</span>&gt;</span>$&#123;knife4j.version&#125;<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">       <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">   <span class="tag">&lt;/<span class="name">dependencies</span>&gt;</span></span><br><span class="line">   <span class="tag">&lt;<span class="name">dependencyManagement</span>&gt;</span></span><br><span class="line">       <span class="tag">&lt;<span class="name">dependencies</span>&gt;</span></span><br><span class="line">           <span class="comment">&lt;!--引入SpringBoot依赖管理清单--&gt;</span></span><br><span class="line">           <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">               <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">               <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-dependencies<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">               <span class="tag">&lt;<span class="name">version</span>&gt;</span>$&#123;spring-boot.version&#125;<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">               <span class="tag">&lt;<span class="name">type</span>&gt;</span>pom<span class="tag">&lt;/<span class="name">type</span>&gt;</span></span><br><span class="line">               <span class="tag">&lt;<span class="name">scope</span>&gt;</span>import<span class="tag">&lt;/<span class="name">scope</span>&gt;</span></span><br><span class="line">           <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">       <span class="tag">&lt;/<span class="name">dependencies</span>&gt;</span></span><br><span class="line">   <span class="tag">&lt;/<span class="name">dependencyManagement</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h4 id="2-3、创建配置文件"><a href="#2-3、创建配置文件" class="headerlink" title="2.3、创建配置文件"></a>2.3、创建配置文件</h4><p>在<code>resourcese</code>下创建配置文件 <code>application.yml</code></p>
<figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Web服务端口号</span></span><br><span class="line"><span class="attr">server:</span></span><br><span class="line">  <span class="attr">port:</span> <span class="number">8080</span></span><br></pre></td></tr></table></figure>

<h4 id="2-4、创建启动类"><a href="#2-4、创建启动类" class="headerlink" title="2.4、创建启动类"></a>2.4、创建启动类</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.wwj.java.ai.langchain4j;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> org.springframework.boot.SpringApplication;</span><br><span class="line"><span class="keyword">import</span> org.springframework.boot.autoconfigure.SpringBootApplication;</span><br><span class="line"></span><br><span class="line"><span class="meta">@SpringBootApplication</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">XiaozhiApp</span> &#123;</span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">		SpringApplication.run(XiaozhiApp.class, args);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="2-5、启动启动类"><a href="#2-5、启动启动类" class="headerlink" title="2.5、启动启动类"></a>2.5、启动启动类</h4><p>访问 <a target="_blank" rel="noopener" href="http://localhost:8080/doc.html">http://localhost:8080/doc.html</a> 查看程序能否成功运行</p>
<h3 id="3、接入大模型"><a href="#3、接入大模型" class="headerlink" title="3、接入大模型"></a>3、接入大模型</h3><p>参考文档：<a target="_blank" rel="noopener" href="https://docs.langchain4j.dev/get-started">https://docs.langchain4j.dev/get-started</a></p>
<h4 id="3-1、LangChain4j-库结构"><a href="#3-1、LangChain4j-库结构" class="headerlink" title="3.1、LangChain4j 库结构"></a>3.1、LangChain4j 库结构</h4><p>LangChain4j 具有模块化设计，包括： </p>
<ol>
<li>langchain4j-core 模块，它定义了核心抽象概念（如聊天语言模型和嵌入存储）及其 API。 </li>
<li>主 langchain4j 模块，包含有用的工具，如文档加载器、聊天记忆实现，以及诸如人工智能服务等 高层功能。</li>
<li>大量的 langchain4j-{集成} 模块，每个模块都将各种大语言模型提供商和嵌入存储集成到  LangChain4j 中。你可以独立使用 langchain4j-{集成} 模块。如需更多功能，只需导入主 langchain4j  依赖项即可。</li>
</ol>
<h4 id="3-2、添加LangChain4j相关依赖"><a href="#3-2、添加LangChain4j相关依赖" class="headerlink" title="3.2、添加LangChain4j相关依赖"></a>3.2、添加LangChain4j相关依赖</h4><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">properties</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">langchain4j.version</span>&gt;</span>1.0.0-beta3<span class="tag">&lt;/<span class="name">langchain4j.version</span>&gt;</span></span><br><span class="line"> <span class="tag">&lt;/<span class="name">properties</span>&gt;</span></span><br><span class="line"> <span class="tag">&lt;<span class="name">dependencies</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 基于open-ai的langchain4j接口：ChatGPT、deepseek都是open-ai标准下的大模型 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>dev.langchain4j<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>langchain4j-open-ai<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"> <span class="tag">&lt;/<span class="name">dependencies</span>&gt;</span></span><br><span class="line"> <span class="tag">&lt;<span class="name">dependencyManagement</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">dependencies</span>&gt;</span></span><br><span class="line">        <span class="comment">&lt;!--引入langchain4j依赖管理清单--&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>dev.langchain4j<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>langchain4j-bom<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">version</span>&gt;</span>$&#123;langchain4j.version&#125;<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">type</span>&gt;</span>pom<span class="tag">&lt;/<span class="name">type</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">scope</span>&gt;</span>import<span class="tag">&lt;/<span class="name">scope</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">dependencies</span>&gt;</span></span><br><span class="line"> <span class="tag">&lt;/<span class="name">dependencyManagement</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h4 id="3-3、创建测试用例"><a href="#3-3、创建测试用例" class="headerlink" title="3.3、创建测试用例"></a>3.3、创建测试用例</h4><p>接入任何一个大模型都需要先去申请 ApiKey</p>
<p>如果你暂时没有密钥，也可以使用LangChain4j 提供的演示密钥，这个密钥是免费的，有使用配额限制， 且仅限于 gpt-4o-mini 模型。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.wwj.java.ai.langchain4j;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> dev.langchain4j.model.openai.OpenAiChatModel;</span><br><span class="line"><span class="keyword">import</span> org.junit.jupiter.api.Test;</span><br><span class="line"><span class="keyword">import</span> org.springframework.boot.test.context.SpringBootTest;</span><br><span class="line"></span><br><span class="line"><span class="meta">@SpringBootTest</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">LLMTest</span> &#123;</span><br><span class="line">	<span class="meta">@Test</span></span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">testGPT</span><span class="params">()</span> &#123;</span><br><span class="line">		<span class="type">OpenAiChatModel</span> <span class="variable">model</span> <span class="operator">=</span> OpenAiChatModel.builder()</span><br><span class="line">				.baseUrl(<span class="string">&quot;http://langchain4j.dev/demo/openai/v1&quot;</span>)</span><br><span class="line">				.apiKey(<span class="string">&quot;demo&quot;</span>)</span><br><span class="line">				.modelName(<span class="string">&quot;gpt-4o-mini&quot;</span>)</span><br><span class="line">				.build();</span><br><span class="line">		<span class="type">String</span> <span class="variable">answer</span> <span class="operator">=</span> model.chat(<span class="string">&quot;你好，你都会做些什么&quot;</span>);</span><br><span class="line">		System.out.println(answer);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="4、SpringBoot整合"><a href="#4、SpringBoot整合" class="headerlink" title="4、SpringBoot整合"></a>4、SpringBoot整合</h3><p>参考文档：<a target="_blank" rel="noopener" href="https://docs.langchain4j.dev/tutorials/spring-boot-integration">https://docs.langchain4j.dev/tutorials/spring-boot-integration</a></p>
<h4 id="4-1、替换依赖"><a href="#4-1、替换依赖" class="headerlink" title="4.1、替换依赖"></a>4.1、替换依赖</h4><p>将 <code>langchain4j-open-ai</code> 替换成  <code>langchain4j-open-ai-spring-boot-starter</code></p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>dev.langchain4j<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>langchain4j-open-ai-spring-boot-starter<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h4 id="4-2、在application-yml中配置模型参数"><a href="#4-2、在application-yml中配置模型参数" class="headerlink" title="4.2、在application.yml中配置模型参数"></a>4.2、在application.yml中配置模型参数</h4><figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">langchain4j:</span></span><br><span class="line">  <span class="attr">open-ai:</span></span><br><span class="line">    <span class="attr">chat-model:</span></span><br><span class="line">      <span class="attr">base-url:</span> <span class="string">http://langchain4j.dev/demo/openai/v1</span></span><br><span class="line">      <span class="attr">api-key:</span> <span class="string">demo</span></span><br><span class="line">      <span class="attr">model-name:</span> <span class="string">gpt-4o-mini</span></span><br><span class="line">      <span class="comment"># 应用程序发送给大模型的请求日志与响应日志</span></span><br><span class="line">      <span class="attr">log-requests:</span> <span class="literal">true</span></span><br><span class="line">      <span class="attr">log-responses:</span> <span class="literal">true</span></span><br></pre></td></tr></table></figure>

<h4 id="4-3、创建测试用例"><a href="#4-3、创建测试用例" class="headerlink" title="4.3、创建测试用例"></a>4.3、创建测试用例</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Autowired</span></span><br><span class="line"><span class="keyword">private</span> OpenAiChatModel openAiChatModel;</span><br><span class="line">	</span><br><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">testSpringBoot</span><span class="params">()</span> &#123;</span><br><span class="line">    <span class="type">String</span> <span class="variable">answer</span> <span class="operator">=</span> openAiChatModel.chat(<span class="string">&quot;我是谁？&quot;</span>);</span><br><span class="line">    System.out.println(answer);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h2 id="二、接入其他大模型"><a href="#二、接入其他大模型" class="headerlink" title="二、接入其他大模型"></a>二、接入其他大模型</h2><h3 id="1、都有哪些大模型"><a href="#1、都有哪些大模型" class="headerlink" title="1、都有哪些大模型"></a>1、都有哪些大模型</h3><ul>
<li><p><strong>大语言模型排行榜</strong>：<a target="_blank" rel="noopener" href="https://superclueai.com/">SuperCLUE中文大模型测评基准——评测榜单</a></p>
<p>SuperCLUE 是由国内 CLUE 学术社区于 2023 年 5 月推出的中文通用大模型综合性评测基准。</p>
</li>
<li><p><strong>评测目的</strong>：全面评估中文大模型在语义理解、逻辑推理、代码生成等 10 项基础能力，以及涵盖数 学、物理、社科等 50 多学科的专业能力，旨在回答在通用大模型发展背景下，中文大模型的效果情 况，包括不同任务效果、与国际代表性模型的差距、与人类的效果对比等问题。</p>
</li>
<li><p><strong>特色优势</strong>：针对中文特性任务，如成语、诗歌、字形等设立专项评测，使评测更符合中文语言特 点。通过 3700 多道客观题和匿名对战机制，动态追踪国内外主流模型，如 GPT-4、文心一言、通义 千问等的表现差异，保证评测的客观性和时效性。</p>
</li>
<li><p>行业影响：作为中文领域权威测评社区，其评测结果被学界和产业界广泛引用，例如商汤 “日日新  5.0” 和百度文心大模型均通过 SuperCLUE 验证技术突破，推动了中文 NLP 技术生态的迭代，为中文 大模型的发展和优化提供了重要的参考依据，促进了中文大模型技术的不断进步和应用。</p>
</li>
<li><p><strong>LangChain4j支持接入的大模型</strong>：<a target="_blank" rel="noopener" href="https://docs.langchain4j.dev/integrations/language-models/">Comparison Table of all supported Language Models | LangChain4j</a></p>
</li>
</ul>
<h3 id="2、接入DeepSeek"><a href="#2、接入DeepSeek" class="headerlink" title="2、接入DeepSeek"></a>2、接入DeepSeek</h3><h4 id="1-1、获取开发参数"><a href="#1-1、获取开发参数" class="headerlink" title="1.1、获取开发参数"></a>1.1、获取开发参数</h4><ul>
<li>访问官网：<a target="_blank" rel="noopener" href="https://www.deepseek.com/">DeepSeek | 深度求索</a>  注册账号，获取base_url和api_key，充值</li>
</ul>
<h4 id="1-2、配置开发参数"><a href="#1-2、配置开发参数" class="headerlink" title="1.2、配置开发参数"></a>1.2、配置开发参数</h4><p>为了apikay的安全，建议将其配置在服务器的环境变量中。变量名自定义即可，例如  <code>DEEP_SEEK_API_KEY</code></p>
<h4 id="1-3、配置模型参数"><a href="#1-3、配置模型参数" class="headerlink" title="1.3、配置模型参数"></a>1.3、配置模型参数</h4><p>DeepSeek API文档：<a target="_blank" rel="noopener" href="https://api-docs.deepseek.com/zh-cn/">https://api-docs.deepseek.com/zh-cn/</a> </p>
<p>在 LangChain4j 中，DeepSeek 和 GPT 一样也使用了 OpenAI 的接口标准，因此也使用OpenAiChatModel进 行接入</p>
<figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#DeepSeek</span></span><br><span class="line"> <span class="string">langchain4j.open-ai.chat-model.base-url=https://api.deepseek.com</span></span><br><span class="line"> <span class="string">langchain4j.open-ai.chat-model.api-key=$&#123;DEEP_SEEK_API_KEY&#125;</span></span><br><span class="line"> <span class="comment">#DeepSeek-V3</span></span><br><span class="line"> <span class="string">langchain4j.open-ai.chat-model.model-name=deepseek-chat</span></span><br><span class="line"> <span class="comment">#DeepSeek-R1 推理模型</span></span><br><span class="line"><span class="comment">#langchain4j.open-ai.chat-model.model-name=deepseek-reasoner</span></span><br></pre></td></tr></table></figure>

<h4 id="1-4、测试"><a href="#1-4、测试" class="headerlink" title="1.4、测试"></a>1.4、测试</h4><p>直接使用前面的测试用例即可</p>
<h3 id="3、ollama本地部署"><a href="#3、ollama本地部署" class="headerlink" title="3、ollama本地部署"></a>3、ollama本地部署</h3><h4 id="3-1、为什么要本地部署"><a href="#3-1、为什么要本地部署" class="headerlink" title="3.1、为什么要本地部署"></a>3.1、为什么要本地部署</h4><p>Ollama 是一个本地部署大模型的工具。使用 Ollama 进行本地部署有以下多方面的原因：</p>
<ul>
<li><strong>数据隐私与安全</strong>：对于金融、医疗、法律等涉及大量敏感数据的行业，数据安全至关重要。</li>
<li>离线可用性：在网络不稳定或无法联网的环境中，本地部署的 Ollama 模型仍可正常运行。</li>
<li><strong>降低成本</strong>：云服务通常按使用量收费，长期使用下来费用较高。而 Ollama 本地部署，只需一次性投 入硬件成本，对于需要频繁使用大语言模型且对成本敏感的用户或企业来说，能有效节约成本。</li>
<li><strong>部署流程简单</strong>：只需通过简单的命令 “ollama run &lt; 模型名&gt;”，就可以自动下载并运行所需的模型。</li>
<li><strong>灵活扩展与定制</strong>：可对模型微调，以适配垂直领域需求。</li>
</ul>
<h4 id="3-2、在ollama上部署DeepSeek"><a href="#3-2、在ollama上部署DeepSeek" class="headerlink" title="3.2、在ollama上部署DeepSeek"></a>3.2、在ollama上部署DeepSeek</h4><p><strong>官网</strong>： <a target="_blank" rel="noopener" href="https://ollama.com/">https://ollama.com/</a></p>
<p>（1）下载并安装ollama： <code>OllamaSetup.exe</code></p>
<p>（2）查看模型列表，选择要部署的模型，<strong>模型列表</strong>： <a target="_blank" rel="noopener" href="https://ollama.com/search">Ollama Search</a></p>
<p>（3）执行命令：<code> ollama run deepseek-r1:1.5</code> 运行大模型。如果是第一次运行则会先下载大模型</p>
<h4 id="3-3、常用命令"><a href="#3-3、常用命令" class="headerlink" title="3.3、常用命令"></a>3.3、常用命令</h4><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">Available Commands:</span><br><span class="line">  serve       Start ollama</span><br><span class="line">  create      Create a model from a Modelfile</span><br><span class="line">  show        Show information for a model</span><br><span class="line">  run         Run a model</span><br><span class="line">  stop        Stop a running model</span><br><span class="line">  pull        Pull a model from a registry</span><br><span class="line">  push        Push a model to a registry</span><br><span class="line">  list        List models</span><br><span class="line">  ps          List running models</span><br><span class="line">  cp          Copy a model</span><br><span class="line">  rm          Remove a model</span><br><span class="line">  help        Help about any command</span><br></pre></td></tr></table></figure>

<h4 id="3-4、引入依赖"><a href="#3-4、引入依赖" class="headerlink" title="3.4、引入依赖"></a>3.4、引入依赖</h4><p>参考文档：<a target="_blank" rel="noopener" href="https://docs.langchain4j.dev/integrations/language-models/ollama#get-started">https://docs.langchain4j.dev/integrations/language-models/ollama#get-started</a></p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- 接入ollama --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>dev.langchain4j<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>langchain4j-ollama-spring-boot-starter<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h4 id="3-5、配置模型参数"><a href="#3-5、配置模型参数" class="headerlink" title="3.5、配置模型参数"></a>3.5、配置模型参数</h4><figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#ollama</span></span><br><span class="line"> <span class="string">langchain4j.ollama.chat-model.base-url=http://localhost:11434</span></span><br><span class="line"> <span class="string">langchain4j.ollama.chat-model.model-name=deepseek-r1:1.5b</span></span><br><span class="line"> <span class="string">langchain4j.ollama.chat-model.log-requests=true</span></span><br><span class="line"> <span class="string">langchain4j.ollama.chat-model.log-responses=true</span></span><br></pre></td></tr></table></figure>

<h4 id="3-6、创建测试用例"><a href="#3-6、创建测试用例" class="headerlink" title="3.6、创建测试用例"></a>3.6、创建测试用例</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * ollama接入</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="meta">@Autowired</span></span><br><span class="line"><span class="keyword">private</span> OllamaChatModel ollamaChatModel;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">testOllama</span><span class="params">()</span> &#123;</span><br><span class="line">    <span class="type">String</span> <span class="variable">answer</span> <span class="operator">=</span> ollamaChatModel.chat(<span class="string">&quot;你是谁？&quot;</span>);</span><br><span class="line">    System.out.println(answer);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="4、接入阿里百炼平台"><a href="#4、接入阿里百炼平台" class="headerlink" title="4、接入阿里百炼平台"></a>4、接入阿里百炼平台</h3><h4 id="4-1、什么是阿里百炼"><a href="#4-1、什么是阿里百炼" class="headerlink" title="4.1、什么是阿里百炼"></a>4.1、什么是阿里百炼</h4><ul>
<li>阿里云百炼是 2023 年 10 月推出的。它集成了阿里的通义系列大模型和第三方大模型，涵盖文本、 图像、音视频等不同模态。</li>
<li><strong>功能优势</strong>：集成超百款大模型 API，模型选择丰富；5-10 分钟就能低代码快速构建智能体，应用构 建高效；提供全链路模型训练、评估工具及全套应用开发工具，模型服务多元；在线部署可按需扩 缩容，新用户有千万 token 免费送，业务落地成本低。</li>
<li><strong>支持接入的模型列表</strong>：<a target="_blank" rel="noopener" href="https://help.aliyun.com/zh/model-studio/models">https://help.aliyun.com/zh/model-studio/models</a></li>
<li><strong>模型广场</strong>：<a target="_blank" rel="noopener" href="https://bailian.console.aliyun.com/?productCode=p_efm#/model-market">https://bailian.console.aliyun.com/?productCode=p_efm#/model-market</a></li>
</ul>
<h4 id="4-2、申请免费体验"><a href="#4-2、申请免费体验" class="headerlink" title="4.2、申请免费体验"></a>4.2、申请免费体验</h4><p>（1）点击进入免费体验页面：<a target="_blank" rel="noopener" href="https://bailian.console.aliyun.com/?tab=model#/model-market">百炼控制台</a></p>
<p>（2）登录选择<code>API-Key</code>，创建并复制自己的<code>API-Key</code></p>
<h4 id="4-3、添加依赖"><a href="#4-3、添加依赖" class="headerlink" title="4.3、添加依赖"></a>4.3、添加依赖</h4><p>LangChain4j参考文档：<a target="_blank" rel="noopener" href="https://docs.langchain4j.dev/integrations/language-models/dashscope#plain-java">https://docs.langchain4j.dev/integrations/language-models/dashscope#plain-java</a></p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependencies</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!-- 接入阿里云百炼平台 --&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>dev.langchain4j<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>langchain4j-community-dashscope-spring-boot-starter<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependencies</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependencyManagement</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;<span class="name">dependencies</span>&gt;</span></span><br><span class="line">     <span class="comment">&lt;!--引入百炼依赖管理清单--&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>dev.langchain4j<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>langchain4j-community-bom<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">version</span>&gt;</span>$&#123;langchain4j.version&#125;<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">type</span>&gt;</span>pom<span class="tag">&lt;/<span class="name">type</span>&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">scope</span>&gt;</span>import<span class="tag">&lt;/<span class="name">scope</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">dependencies</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependencyManagement</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h4 id="4-4、配置模型参数"><a href="#4-4、配置模型参数" class="headerlink" title="4.4、配置模型参数"></a>4.4、配置模型参数</h4><figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">langchain4j:</span></span><br><span class="line">  <span class="comment">#阿里百练平台</span></span><br><span class="line">  <span class="attr">community:</span></span><br><span class="line">    <span class="attr">dashscope:</span></span><br><span class="line">      <span class="attr">chat-model:</span></span><br><span class="line">        <span class="attr">api-key:</span> <span class="string">sk-46c3383686324d6298a1e6549bf815b2</span></span><br><span class="line">        <span class="attr">model-name:</span> <span class="string">qwen-max</span></span><br></pre></td></tr></table></figure>

<h4 id="4-5、测试通义千问"><a href="#4-5、测试通义千问" class="headerlink" title="4.5、测试通义千问"></a>4.5、测试通义千问</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Autowired</span></span><br><span class="line"><span class="keyword">private</span> QwenChatModel qwenChatModel;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">testQwen</span><span class="params">()</span> &#123;</span><br><span class="line">    <span class="type">String</span> <span class="variable">answer</span> <span class="operator">=</span> qwenChatModel.chat(<span class="string">&quot;你是谁？&quot;</span>);</span><br><span class="line">    System.out.println(answer);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="4-6、测试通义万象"><a href="#4-6、测试通义万象" class="headerlink" title="4.6、测试通义万象"></a>4.6、测试通义万象</h4><p>生成图片测试</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">testQwen</span><span class="params">()</span> &#123;</span><br><span class="line">	<span class="type">WanxImageModel</span> <span class="variable">wanxImageModel</span> <span class="operator">=</span> WanxImageModel.builder()</span><br><span class="line">			.modelName(<span class="string">&quot;wanx2.1-t2i-turbo&quot;</span>)</span><br><span class="line">			.apiKey(<span class="string">&quot;sk-xxxxxxxxxxx&quot;</span>)</span><br><span class="line">			.build();</span><br><span class="line">	Response&lt;Image&gt; response = wanxImageModel.generate(<span class="string">&quot;奇幻森林精灵：在一片弥漫着轻柔薄雾的古老森林深处，阳光透过茂密枝叶洒下金色光斑。一位身材娇小、长着透明薄翼的精灵少女站在一朵硕大的蘑菇上。她有着海藻般的绿色长发，发间点缀着蓝色的小花，皮肤泛着珍珠般的微光。身上穿着由翠绿树叶和白色藤蔓编织而成的连衣裙，手中捧着一颗散发着柔和光芒的水晶球，周围环绕着五彩斑斓的蝴蝶，脚下是铺满苔藓的地面，蘑菇和蕨类植物丛生，营造出神秘而梦幻的氛围。&quot;</span>);</span><br><span class="line">	<span class="type">URI</span> <span class="variable">url</span> <span class="operator">=</span> response.content().url();</span><br><span class="line">	System.out.println(url);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h2 id="三、人工智能服务-AIService"><a href="#三、人工智能服务-AIService" class="headerlink" title="三、人工智能服务 AIService"></a>三、人工智能服务 AIService</h2><h3 id="1、什么是AIService"><a href="#1、什么是AIService" class="headerlink" title="1、什么是AIService"></a>1、什么是AIService</h3><p>AIService使用面向接口和动态代理的方式完成程序的编写，更灵活的实现高级功能。</p>
<h4 id="1-1、链-Chain（旧版）"><a href="#1-1、链-Chain（旧版）" class="headerlink" title="1.1、链 Chain（旧版）"></a>1.1、链 Chain（旧版）</h4><p>链的概念源自 Python 中的 LangChain。其理念是针对每个常见的用例都设置一条链，比如聊天机器人、 检索增强生成（RAG）等。链将多个底层组件组合起来，并协调它们之间的交互。链存在的主要问题是不 灵活，我们不进行深入的研究。</p>
<h4 id="1-2、人工智能服务-AIService"><a href="#1-2、人工智能服务-AIService" class="headerlink" title="1.2、人工智能服务 AIService"></a>1.2、人工智能服务 AIService</h4><p>在LangChain4j中我们使用AIService完成复杂操作。底层组件将由AIService进行组装。</p>
<p><strong>AIService可处理最常见的操作：</strong></p>
<ul>
<li>为大语言模型格式化输入内容</li>
<li>解析大语言模型的输出结果</li>
</ul>
<p><strong>它们还支持更高级的功能：</strong></p>
<ul>
<li>聊天记忆 Chat memory</li>
<li>工具 Tools</li>
<li>检索增强生成 RAG</li>
</ul>
<h3 id="2、创建AIService"><a href="#2、创建AIService" class="headerlink" title="2、创建AIService"></a>2、创建AIService</h3><h4 id="2-1、引入依赖"><a href="#2-1、引入依赖" class="headerlink" title="2.1、引入依赖"></a>2.1、引入依赖</h4><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!--langchain4j高级功能--&gt;</span></span><br><span class="line"> <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>dev.langchain4j<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>langchain4j-spring-boot-starter<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line"> <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h4 id="2-2、创建接口"><a href="#2-2、创建接口" class="headerlink" title="2.2、创建接口"></a>2.2、创建接口</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.wwj.java.ai.langchain4j.assistant;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">Assistant</span> &#123;</span><br><span class="line">	String <span class="title function_">chat</span><span class="params">(String userMessage)</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="2-3、测试用例"><a href="#2-3、测试用例" class="headerlink" title="2.3、测试用例"></a>2.3、测试用例</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@SpringBootTest</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">AIServiceTest</span> &#123;</span><br><span class="line">	<span class="meta">@Autowired</span></span><br><span class="line">	<span class="keyword">private</span> QwenChatModel qwenChatModel;</span><br><span class="line">	</span><br><span class="line">	<span class="meta">@Test</span></span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">testChat</span><span class="params">()</span> &#123;</span><br><span class="line">		<span class="type">Assistant</span> <span class="variable">assistant</span> <span class="operator">=</span> AiServices.create(Assistant.class, qwenChatModel);</span><br><span class="line">		<span class="type">String</span> <span class="variable">answer</span> <span class="operator">=</span> assistant.chat(<span class="string">&quot;你是谁？&quot;</span>);</span><br><span class="line">		System.out.println(answer);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="2-4、-AiService"><a href="#2-4、-AiService" class="headerlink" title="2.4、@AiService"></a>2.4、@AiService</h4><p>也可以在 <code>Assistant 接口</code>上添加 <code>@AiService</code> 注解</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> dev.langchain4j.service.spring.AiService;</span><br><span class="line"><span class="keyword">import</span> <span class="keyword">static</span> dev.langchain4j.service.spring.AiServiceWiringMode.EXPLICIT;</span><br><span class="line"></span><br><span class="line"><span class="comment">//因为我们在配置文件中同时配置了多个大语言模型，所以需要在这里明确指定（EXPLICIT）模型的beanName</span></span><br><span class="line"><span class="meta">@AiService(wiringMode = EXPLICIT, chatModel = &quot;qwenChatModel&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">Assistant</span> &#123;</span><br><span class="line">	String <span class="title function_">chat</span><span class="params">(String userMessage)</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>测试用例中，我们可以直接注入Assistant对象</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Autowired</span></span><br><span class="line"><span class="keyword">private</span> Assistant assistant;</span><br><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">testAssistant</span><span class="params">()</span> &#123;</span><br><span class="line">    <span class="type">String</span> <span class="variable">answer</span> <span class="operator">=</span> assistant.chat(<span class="string">&quot;你是谁？&quot;</span>);</span><br><span class="line">    System.out.println(answer);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="2-5、工作原理"><a href="#2-5、工作原理" class="headerlink" title="2.5、工作原理"></a>2.5、工作原理</h4><p>AiServices会<strong>组装Assistant接口以及其他组件</strong>，并使用反射机制创建一个实现Assistant接口的<strong>代理对象</strong>。 这个代理对象会处理输入和输出的所有转换工作。在这个例子中，chat方法的输入是一个字符串，但是大 模型需要一个 **UserMessage **对象。所以，代理对象将这个字符串转换为 <strong>UserMessage</strong> ，并调用聊天语 言模型。chat方法的输出类型也是字符串，但是大模型返回的是  <strong>AiMessage</strong> 对象，代理对象会将其转换 为字符串。 简单理解就是：代理对象的作用是输入转换和输出转换</p>
<blockquote>
<p>简单理解就是：代理对象的作用是输入转换和输出转换</p>
</blockquote>
<h2 id="四、聊天记忆-Chat-memory"><a href="#四、聊天记忆-Chat-memory" class="headerlink" title="四、聊天记忆 Chat memory"></a>四、聊天记忆 Chat memory</h2><h3 id="1、测试对话是否有记忆"><a href="#1、测试对话是否有记忆" class="headerlink" title="1、测试对话是否有记忆"></a>1、测试对话是否有记忆</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@SpringBootTest</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ChatMemoryTest</span> &#123;</span><br><span class="line">	</span><br><span class="line">	<span class="meta">@Autowired</span></span><br><span class="line">	<span class="keyword">private</span> Assistant assistant;</span><br><span class="line">	<span class="meta">@Test</span></span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">testChatMemory</span><span class="params">()</span> &#123;</span><br><span class="line">		<span class="comment">// 创建一个会话</span></span><br><span class="line">		<span class="type">String</span> <span class="variable">answer1</span> <span class="operator">=</span> assistant.chat(<span class="string">&quot;我是坏坏&quot;</span>);</span><br><span class="line">		System.out.println(answer1);</span><br><span class="line">		<span class="type">String</span> <span class="variable">answer2</span> <span class="operator">=</span> assistant.chat(<span class="string">&quot;我是谁？&quot;</span>);</span><br><span class="line">		System.out.println(answer2);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>answer1：你好，坏坏！有什么我可以帮助你的吗？或者你想聊些什么呢？</p>
<p>answer2：您好！您是使用这个平台的用户，但我无法直接知道您的具体身份信息，因为我重视并保护用户的隐私。如果您想分享更多信息关于您自己，我很乐意进一步交流！或者，如果您有其他想要了解的问题或需要帮助的地方，请告诉我。</p>
</blockquote>
<p>很显然，目前的接入方式，大模型是没有记忆的。</p>
<h3 id="2、聊天记忆的简单实现"><a href="#2、聊天记忆的简单实现" class="headerlink" title="2、聊天记忆的简单实现"></a>2、聊天记忆的简单实现</h3><p>可以使用下面的方式实现对话记忆。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Autowired</span></span><br><span class="line"><span class="keyword">private</span> QwenChatModel qwenChatModel;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">testChatMemory2</span><span class="params">()</span> &#123;</span><br><span class="line">    <span class="comment">// 第一轮对话</span></span><br><span class="line">    <span class="type">UserMessage</span> <span class="variable">userMessage1</span> <span class="operator">=</span> UserMessage.userMessage(<span class="string">&quot;我是坏坏&quot;</span>);</span><br><span class="line">    <span class="type">ChatResponse</span> <span class="variable">chatResponse1</span> <span class="operator">=</span> qwenChatModel.chat(userMessage1);</span><br><span class="line">    <span class="type">AiMessage</span> <span class="variable">aiMessage1</span> <span class="operator">=</span> chatResponse1.aiMessage();</span><br><span class="line">    System.out.println(aiMessage1.text());</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 第二轮对话</span></span><br><span class="line">    <span class="type">UserMessage</span> <span class="variable">userMessage2</span> <span class="operator">=</span> UserMessage.userMessage(<span class="string">&quot;你知道我是谁吗？&quot;</span>);</span><br><span class="line">    <span class="type">ChatResponse</span> <span class="variable">chatResponse2</span> <span class="operator">=</span> qwenChatModel.chat(Arrays.asList(userMessage1, aiMessage1, userMessage2));</span><br><span class="line">    <span class="type">AiMessage</span> <span class="variable">aiMessage2</span> <span class="operator">=</span> chatResponse2.aiMessage();</span><br><span class="line">    System.out.println(aiMessage2.text());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>第一轮：你好，坏坏！有什么我可以帮助你的吗？或者你想聊些什么呢？</p>
<p>第二轮：你好！根据你提供的信息“我是坏坏”，我了解到你的昵称或名字是“坏坏”。不过，除非你之前和我有过交流并且提供了更多的个人信息，否则我无法知道更多关于你的具体信息。如果你愿意分享更多信息，我会很高兴更好地了解你并提供帮助。有什么特别的事情想要聊聊吗？</p>
</blockquote>
<h3 id="3、使用ChatMemory实现聊天记忆"><a href="#3、使用ChatMemory实现聊天记忆" class="headerlink" title="3、使用ChatMemory实现聊天记忆"></a>3、使用ChatMemory实现聊天记忆</h3><p>使用AIService可以封装多轮对话的复杂性，使聊天记忆功能的实现变得简单</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">testChatMemory3</span><span class="params">()</span> &#123;</span><br><span class="line">    <span class="comment">//创建chatMemory</span></span><br><span class="line">    <span class="type">MessageWindowChatMemory</span> <span class="variable">chatMemory</span> <span class="operator">=</span> MessageWindowChatMemory.withMaxMessages(<span class="number">10</span>);</span><br><span class="line">    <span class="comment">//创建AIService</span></span><br><span class="line">    <span class="type">Assistant</span> <span class="variable">assistant</span> <span class="operator">=</span> AiServices</span><br><span class="line">        .builder(Assistant.class)</span><br><span class="line">        .chatLanguageModel(qwenChatModel)</span><br><span class="line">        .chatMemory(chatMemory)</span><br><span class="line">        .build();</span><br><span class="line">    <span class="comment">//调用service的接口</span></span><br><span class="line">    <span class="type">String</span> <span class="variable">answer1</span> <span class="operator">=</span> assistant.chat(<span class="string">&quot;我是环环&quot;</span>);</span><br><span class="line">    System.out.println(answer1);</span><br><span class="line">    <span class="type">String</span> <span class="variable">answer2</span> <span class="operator">=</span> assistant.chat(<span class="string">&quot;我是谁&quot;</span>);</span><br><span class="line">    System.out.println(answer2);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="4、使用AIService实现聊天记忆"><a href="#4、使用AIService实现聊天记忆" class="headerlink" title="4、使用AIService实现聊天记忆"></a>4、使用AIService实现聊天记忆</h3><h4 id="4-1、创建记忆对话智能体"><a href="#4-1、创建记忆对话智能体" class="headerlink" title="4.1、创建记忆对话智能体"></a>4.1、创建记忆对话智能体</h4><p>当AIService由多个组件（大模型，聊天记忆，等）组成的时候，我们就可以称他为<code>智能体</code>了</p>
<p>我们先创建一个具有记忆功能的智能体接口：<code>MemoryChatAssistant</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.wwj.java.ai.langchain4j.assistant;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> dev.langchain4j.service.spring.AiService;</span><br><span class="line"><span class="keyword">import</span> <span class="keyword">static</span> dev.langchain4j.service.spring.AiServiceWiringMode.EXPLICIT;</span><br><span class="line"></span><br><span class="line"><span class="meta">@AiService(</span></span><br><span class="line"><span class="meta">		wiringMode = EXPLICIT,</span></span><br><span class="line"><span class="meta">		chatModel = &quot;qwenChatModel&quot;,</span></span><br><span class="line"><span class="meta">		chatMemory = &quot;chatMemory&quot;</span></span><br><span class="line"><span class="meta">)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">MemoryChatAssistant</span> &#123;</span><br><span class="line">	String <span class="title function_">chat</span><span class="params">(String message)</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="4-2、配置ChatMemory"><a href="#4-2、配置ChatMemory" class="headerlink" title="4.2、配置ChatMemory"></a>4.2、配置ChatMemory</h4><p>在智能体<code>MemoryChatAssistant</code>接口中的<strong>chatMemory</strong>进行配置，作为<code>Bean</code>注入</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.wwj.java.ai.langchain4j.config;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> dev.langchain4j.memory.ChatMemory;</span><br><span class="line"><span class="keyword">import</span> dev.langchain4j.memory.chat.MessageWindowChatMemory;</span><br><span class="line"><span class="keyword">import</span> org.springframework.context.annotation.Bean;</span><br><span class="line"><span class="keyword">import</span> org.springframework.context.annotation.Configuration;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">MemoryChatAssistantConfig</span> &#123;</span><br><span class="line">	</span><br><span class="line">	<span class="meta">@Bean</span></span><br><span class="line">	<span class="keyword">public</span> ChatMemory <span class="title function_">chatMemory</span><span class="params">()</span> &#123;</span><br><span class="line">		<span class="keyword">return</span> MessageWindowChatMemory.withMaxMessages(<span class="number">10</span>);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="4-3、测试"><a href="#4-3、测试" class="headerlink" title="4.3、测试"></a>4.3、测试</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Autowired</span></span><br><span class="line"><span class="keyword">private</span> MemoryChatAssistant memoryChatAssistant;</span><br><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">testChatMemory4</span><span class="params">()</span> &#123;</span><br><span class="line">    <span class="comment">//调用service的接口</span></span><br><span class="line">    <span class="type">String</span> <span class="variable">answer1</span> <span class="operator">=</span> memoryChatAssistant.chat(<span class="string">&quot;我是环环&quot;</span>);</span><br><span class="line">    System.out.println(answer1);</span><br><span class="line">    <span class="type">String</span> <span class="variable">answer2</span> <span class="operator">=</span> memoryChatAssistant.chat(<span class="string">&quot;我是谁&quot;</span>);</span><br><span class="line">    System.out.println(answer2);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="5、隔离聊天记忆"><a href="#5、隔离聊天记忆" class="headerlink" title="5、隔离聊天记忆"></a>5、隔离聊天记忆</h3><p>为每个用户的新聊天或者不同的用户区分聊天记忆</p>
<h4 id="5-1、创建记忆隔离对话智能体"><a href="#5-1、创建记忆隔离对话智能体" class="headerlink" title="5.1、创建记忆隔离对话智能体"></a>5.1、创建记忆隔离对话智能体</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.wwj.java.ai.langchain4j.assistant;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> dev.langchain4j.service.MemoryId;</span><br><span class="line"><span class="keyword">import</span> dev.langchain4j.service.UserMessage;</span><br><span class="line"><span class="keyword">import</span> dev.langchain4j.service.spring.AiService;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> <span class="keyword">static</span> dev.langchain4j.service.spring.AiServiceWiringMode.EXPLICIT;</span><br><span class="line"></span><br><span class="line"><span class="meta">@AiService(</span></span><br><span class="line"><span class="meta">    wiringMode = EXPLICIT,</span></span><br><span class="line"><span class="meta">    chatModel = &quot;qwenChatModel&quot;,</span></span><br><span class="line"><span class="meta">    chatMemoryProvider = &quot;chatMemoryProvider&quot;</span></span><br><span class="line"><span class="meta">)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">SeparateChatAssistant</span> &#123;</span><br><span class="line">    String <span class="title function_">chat</span><span class="params">(<span class="meta">@MemoryId</span> <span class="type">int</span> memoryId, <span class="meta">@UserMessage</span> String userMessage)</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="5-2、配置ChatMemoryProvider"><a href="#5-2、配置ChatMemoryProvider" class="headerlink" title="5.2、配置ChatMemoryProvider"></a>5.2、配置ChatMemoryProvider</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.wwj.java.ai.langchain4j.config;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> dev.langchain4j.memory.chat.ChatMemoryProvider;</span><br><span class="line"><span class="keyword">import</span> dev.langchain4j.memory.chat.MessageWindowChatMemory;</span><br><span class="line"><span class="keyword">import</span> org.springframework.context.annotation.Bean;</span><br><span class="line"><span class="keyword">import</span> org.springframework.context.annotation.Configuration;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ChatMemoryProviderConfig</span> &#123;</span><br><span class="line">	<span class="meta">@Bean</span></span><br><span class="line">	<span class="keyword">public</span> ChatMemoryProvider <span class="title function_">chatMemoryProvider</span><span class="params">()</span> &#123;</span><br><span class="line">		<span class="keyword">return</span> memoryId -&gt; MessageWindowChatMemory.builder().id(memoryId).maxMessages(<span class="number">10</span>).build();</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="5-3、测试对话助手"><a href="#5-3、测试对话助手" class="headerlink" title="5.3、测试对话助手"></a>5.3、测试对话助手</h4><p>用两个不同的memoryId测试聊天记忆的隔离效果</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Autowired</span></span><br><span class="line"><span class="keyword">private</span> SeparateChatAssistant separateChatAssistant;</span><br><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">testChatMemory5</span><span class="params">()</span> &#123;</span><br><span class="line">    <span class="type">String</span> <span class="variable">answer1</span> <span class="operator">=</span> separateChatAssistant.chat(<span class="number">1</span>,<span class="string">&quot;我是环环&quot;</span>);</span><br><span class="line">    System.out.println(answer1);</span><br><span class="line">    <span class="type">String</span> <span class="variable">answer2</span> <span class="operator">=</span> separateChatAssistant.chat(<span class="number">1</span>,<span class="string">&quot;我是谁&quot;</span>);</span><br><span class="line">    System.out.println(answer2);</span><br><span class="line">    <span class="type">String</span> <span class="variable">answer3</span> <span class="operator">=</span> separateChatAssistant.chat(<span class="number">2</span>,<span class="string">&quot;我是谁&quot;</span>);</span><br><span class="line">    System.out.println(answer3);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>结果如下，只有<code>Id为 1 与 2</code>记忆分开</p>
<blockquote>
<p>answer1：你好，环环！很高兴见到你。有什么我可以帮助你的吗？如果你有任何问题或需要讨论的话题，随时告诉我。</p>
<p>answer2：你刚才告诉我你是环环。如果你是用这个名字来指代自己，那么你就是环环。如果这是一个昵称或者有其他含义，请告诉我更多信息，这样我可以更好地帮助你。</p>
<p>answer3：您是使用这个平台的用户，但我无法直接知道您的具体身份信息，因为我重视并保护用户的隐私。如果您想告诉我更多关于您的信息，我很乐意了解！或者，如果您有任何问题或需要帮助的地方，请随时告诉我。</p>
</blockquote>
<h2 id="五、持久化聊天记忆-Persistence"><a href="#五、持久化聊天记忆-Persistence" class="headerlink" title="五、持久化聊天记忆 Persistence"></a>五、持久化聊天记忆 Persistence</h2><p>默认情况下，聊天记忆存储在内存中。如果需要持久化存储，可以实现一个自定义的聊天记忆存储类， 以便将聊天消息存储在你选择的任何持久化存储介质中。</p>
<h3 id="1、存储介质的选择"><a href="#1、存储介质的选择" class="headerlink" title="1、存储介质的选择"></a>1、存储介质的选择</h3><p>大模型中聊天记忆的存储选择哪种数据库，需要综合考虑数据特点、应用场景和性能要求等因素，以下 是一些常见的选择及其特点：</p>
<ul>
<li>MySQL<ul>
<li><strong>特点</strong>：关系型数据库。支持事务处理，确保数据的一致性和完整性，适用于结构化数据的存储 和查询。</li>
<li><strong>适用场景</strong>：如果聊天记忆数据结构较为规整，例如包含固定的字段如对话 ID、用户 ID、时间 戳、消息内容等，且需要进行复杂的查询和统计分析，如按用户统计对话次数、按时间范围查 询特定对话等，MySQL 是不错的选择。</li>
</ul>
</li>
<li>Redis <ul>
<li><strong>特点</strong>：内存数据库，读写速度极高。它适用于存储热点数据，并且支持多种数据结构，如字符 串、哈希表、列表等，方便对不同类型的聊天记忆数据进行处理。 </li>
<li><strong>适用场景</strong>：对于实时性要求极高的聊天应用，如在线客服系统或即时通讯工具，Redis 可以快 速存储和获取最新的聊天记录，以提供流畅的聊天体验。</li>
</ul>
</li>
<li>MongoDB <ul>
<li><strong>特点</strong>：文档型数据库，数据以 JSON - like 的文档形式存储，具有高度的灵活性和可扩展性。它 不需要预先定义严格的表结构，适合存储半结构化或非结构化的数据。 </li>
<li><strong>适用场景</strong>：当聊天记忆中包含多样化的信息，如文本消息、图片、语音等多媒体数据，或者消 息格式可能会频繁变化时，MongoDB 能很好地适应这种灵活性。例如，一些社交应用中用户可 能会发送各种格式的消息，使用 MongoDB 可以方便地存储和管理这些不同类型的数据。</li>
</ul>
</li>
<li>Cassandra<ul>
<li><strong>特点</strong>：是一种分布式的 NoSQL 数据库，具有高可扩展性和高可用性，能够处理大规模的分布 式数据存储和读写请求。适合存储海量的、时间序列相关的数据。 </li>
<li><strong>适用场景</strong>：对于大型的聊天应用，尤其是用户量众多、聊天数据量巨大且需要分布式存储和处 理的场景，Cassandra 能够有效地应对高并发的读写操作。例如，一些面向全球用户的社交媒 体平台，其聊天数据需要在多个节点上进行分布式存储和管理，Cassandra 可以提供强大的支 持。</li>
</ul>
</li>
</ul>
<h3 id="2、MongoDB"><a href="#2、MongoDB" class="headerlink" title="2、MongoDB"></a>2、MongoDB</h3><h4 id="2-1、简介"><a href="#2-1、简介" class="headerlink" title="2.1、简介"></a>2.1、简介</h4><p>MongoDB 是一个基于文档的 NoSQL 数据库，由 MongoDB Inc. 开发。</p>
<p>NoSQL，指的是<strong>非关系型</strong>的数据库。NoSQL有时也称作Not Only SQL的缩写，是对不同于传统的关系型数 据库的数据库管理系统的统称。</p>
<p>MongoDB 的设计理念是为了应对大数据量、高性能和灵活性需求。 </p>
<p>MongoDB使用集合（Collections）来组织文档（Documents），每个文档都是由键值对组成的。</p>
<ul>
<li><strong>数据库（Database）</strong>：存储数据的容器，类似于关系型数据库中的数据库。 </li>
<li><strong>集合（Collection）</strong>：数据库中的一个集合，类似于关系型数据库中的表。 </li>
<li><strong>文档（Document）</strong>：集合中的一个数据记录，类似于关系型数据库中的行（row），以 BSON 格式 存储。</li>
</ul>
<p>MongoDB 将数据存储为一个文档，数据结构由键值(key&#x3D;&gt;value)对组成，文档类似于 JSON 对象，字段值 可以包含其他文档，数组及文档数组：</p>
<p><img src="/../images/202504252303548.png" alt="MongoDB数据存储"></p>
<h4 id="2-2、安装MongoDB"><a href="#2-2、安装MongoDB" class="headerlink" title="2.2、安装MongoDB"></a>2.2、安装MongoDB</h4><p>服务器： <code>mongodb-windows-x86_64-8.0.6-signed.msi</code>： <a target="_blank" rel="noopener" href="https://www.mongodb.com/try/download/community">https://www.mongodb.com/try/download/community</a> </p>
<p>命令行客户端 ： <code>mongosh-2.5.0-win32-x64.zip</code>： <a target="_blank" rel="noopener" href="https://www.mongodb.com/try/download/shell">https://www.mongodb.com/try/download/shell</a> </p>
<p>图形客户端： <code>mongodb-compass-1.39.3-win32-x64.exe</code>： <a target="_blank" rel="noopener" href="https://www.mongodb.com/try/download/compass">https://www.mongodb.com/try/download/compass</a></p>
<h4 id="2-3、使用mongosh"><a href="#2-3、使用mongosh" class="headerlink" title="2.3、使用mongosh"></a>2.3、使用mongosh</h4><p><strong>启动 MongoDB Shell：</strong> </p>
<p>在命令行中输入 mongosh 命令，启动 MongoDB Shell，如果 MongoDB 服务器运行在本地默认端口 （27017），则可以直接连接</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">mongosh</span><br></pre></td></tr></table></figure>

<p>连接到 MongoDB 服务器： 如果 MongoDB 服务器运行在非默认端口或者远程服务器上，可以使用以下命令连接：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">mongosh --host &lt;hostname&gt;:&lt;port&gt;</span><br></pre></td></tr></table></figure>

<p>其中 <code>&lt;hostname&gt;</code> 是 MongoDB 服务器的主机名或 IP 地址，<code>&lt;port&gt;</code>是 MongoDB 服务器的端口号。</p>
<p><strong>执行基本操作：</strong> 	</p>
<p>连接成功后，可以执行各种 MongoDB 数据库操作。例如：</p>
<ul>
<li>查看当前数据库：<code>db </code></li>
<li>显示数据库列表：<code>show dbs</code></li>
<li>切换到指定数据库：<code>use &lt;database_name&gt;</code></li>
<li>执行查询操作： <code>db.&lt;collection_name&gt;.find()</code></li>
<li>插入文档： <code>db.&lt;collection_name&gt;.insertOne(&#123;  ...  &#125;)</code></li>
<li>更新文档：<code>db.&lt;collection_name&gt;.updateOne(&#123; ... &#125;)</code></li>
<li>删除文档：<code>db.&lt;collection_name&gt;.deleteOne(&#123;  ...  &#125;)</code></li>
<li>退出 MongoDB Shell：<code>quit()</code> 或者 <code>exit</code></li>
</ul>
<p> <strong>CRUD</strong></p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_"># </span><span class="language-bash">插入文档</span></span><br><span class="line">db.mycollection.insertOne(&#123; name: &quot;Alice&quot;, age: 30 &#125;)</span><br><span class="line"><span class="meta prompt_"> # </span><span class="language-bash">查询文档</span></span><br><span class="line">db.mycollection.find()</span><br><span class="line"><span class="meta prompt_"> # </span><span class="language-bash">更新文档</span></span><br><span class="line">db.mycollection.updateOne(&#123; name: &quot;Alice&quot; &#125;, &#123; $set: &#123; age: 31 &#125; &#125;)</span><br><span class="line"><span class="meta prompt_"> # </span><span class="language-bash">删除文档</span></span><br><span class="line">db.mycollection.deleteOne(&#123; name: &quot;Alice&quot; &#125;)</span><br><span class="line"><span class="meta prompt_"> # </span><span class="language-bash">退出 MongoDB Shell</span></span><br><span class="line"><span class="meta prompt_"> test&gt;</span><span class="language-bash">quit()</span></span><br></pre></td></tr></table></figure>

<h4 id="2-4、使用mongodb-compass"><a href="#2-4、使用mongodb-compass" class="headerlink" title="2.4、使用mongodb-compass"></a>2.4、使用mongodb-compass</h4><p>可以通过<code>mongodb-compass</code>可视化工具直接操作mongoDB的集合。</p>
<h4 id="2-5、整合SpringBoot"><a href="#2-5、整合SpringBoot" class="headerlink" title="2.5、整合SpringBoot"></a>2.5、整合SpringBoot</h4><p>引入MongoDB依赖：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- Spring Boot Starter Data MongoDB --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-data-mongodb<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>添加远程连接配置：</p>
<figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#MongoDB连接配置</span></span><br><span class="line"><span class="attr">spring:</span></span><br><span class="line">  <span class="attr">data:</span></span><br><span class="line">    <span class="attr">mongodb:</span></span><br><span class="line">            <span class="attr">uri:</span> <span class="string">mongodb://localhost:27017/chat_memory_db</span></span><br></pre></td></tr></table></figure>

<p>如果新增了用户与密码使用如下：</p>
<figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">spring:</span></span><br><span class="line">  <span class="attr">data:</span></span><br><span class="line">    <span class="attr">mongodb:</span></span><br><span class="line">      <span class="attr">uri:</span> <span class="string">mongodb://mongo:123456@10.11.12.13:27017/chat_memory_db?authSource=admin</span></span><br></pre></td></tr></table></figure>

<h4 id="2-6、CRUD测试"><a href="#2-6、CRUD测试" class="headerlink" title="2.6、CRUD测试"></a>2.6、CRUD测试</h4><p>创建实体类：映射MongoDB中的文档（相当与MySQL的表）</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.wwj.java.ai.langchain4j.bean;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Data</span></span><br><span class="line"><span class="meta">@AllArgsConstructor</span></span><br><span class="line"><span class="meta">@NoArgsConstructor</span></span><br><span class="line"><span class="meta">@Document(&quot;chat_messages&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ChatMessages</span> &#123;</span><br><span class="line">	<span class="comment">//唯一标识，映射到 MongoDB 文档的 _id 字段</span></span><br><span class="line">	<span class="meta">@Id</span></span><br><span class="line">	<span class="keyword">private</span> ObjectId messageId;</span><br><span class="line">	<span class="comment">//private Long messageId;</span></span><br><span class="line">	</span><br><span class="line">	<span class="keyword">private</span> String content; <span class="comment">//存储当前聊天记录列表的json字符串</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>创建测试类：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.wwj.java.ai.langchain4j;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.wwj.java.ai.langchain4j.bean.ChatMessages;</span><br><span class="line"><span class="keyword">import</span> org.junit.jupiter.api.Test;</span><br><span class="line"><span class="keyword">import</span> org.springframework.beans.factory.annotation.Autowired;</span><br><span class="line"><span class="keyword">import</span> org.springframework.boot.test.context.SpringBootTest;</span><br><span class="line"><span class="keyword">import</span> org.springframework.data.mongodb.core.MongoTemplate;</span><br><span class="line"><span class="keyword">import</span> org.springframework.data.mongodb.core.query.Criteria;</span><br><span class="line"><span class="keyword">import</span> org.springframework.data.mongodb.core.query.Query;</span><br><span class="line"><span class="keyword">import</span> org.springframework.data.mongodb.core.query.Update;</span><br><span class="line"></span><br><span class="line"><span class="meta">@SpringBootTest</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">MongoCrudTest</span> &#123;</span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> MongoTemplate mongoTemplate;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * 插入文档</span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">    <span class="comment">//    @Test</span></span><br><span class="line">    <span class="comment">//    public void testInsert() &#123;</span></span><br><span class="line">    <span class="comment">//        mongoTemplate.insert(new ChatMessages(1L, &quot;聊天记录&quot;));</span></span><br><span class="line">    <span class="comment">//    &#125;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * 插入文档</span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">testInsert2</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="type">ChatMessages</span> <span class="variable">chatMessages</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ChatMessages</span>();</span><br><span class="line">        chatMessages.setContent(<span class="string">&quot;聊天记录列表&quot;</span>);</span><br><span class="line">        mongoTemplate.insert(chatMessages);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * 根据id查询文档</span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">testFindById</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="type">ChatMessages</span> <span class="variable">chatMessages</span> <span class="operator">=</span> mongoTemplate.findById(<span class="string">&quot;680e4cfc53eeba4ef57db43f&quot;</span>,</span><br><span class="line">                                                           ChatMessages.class);</span><br><span class="line">        System.out.println(chatMessages);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * 修改文档</span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">testUpdate</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="type">Criteria</span> <span class="variable">criteria</span> <span class="operator">=</span> Criteria.where(<span class="string">&quot;_id&quot;</span>).is(<span class="string">&quot;680e4cfc53eeba4ef57db43f&quot;</span>);</span><br><span class="line">        <span class="type">Query</span> <span class="variable">query</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Query</span>(criteria);</span><br><span class="line">        <span class="type">Update</span> <span class="variable">update</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Update</span>();</span><br><span class="line">        update.set(<span class="string">&quot;content&quot;</span>, <span class="string">&quot;新的聊天记录列表&quot;</span>);</span><br><span class="line">        <span class="comment">// 修改或新增</span></span><br><span class="line">        mongoTemplate.upsert(query, update, ChatMessages.class);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * 删除文档</span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">testDelete</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="type">Criteria</span> <span class="variable">criteria</span> <span class="operator">=</span> Criteria.where(<span class="string">&quot;_id&quot;</span>).is(<span class="string">&quot;680e4cfc53eeba4ef57db43f&quot;</span>);</span><br><span class="line">        <span class="type">Query</span> <span class="variable">query</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Query</span>(criteria);</span><br><span class="line">        mongoTemplate.remove(query, ChatMessages.class);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="3、持久化聊天"><a href="#3、持久化聊天" class="headerlink" title="3、持久化聊天"></a>3、持久化聊天</h3><h4 id="3-1、优化实体类"><a href="#3-1、优化实体类" class="headerlink" title="3.1、优化实体类"></a>3.1、优化实体类</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.wwj.java.ai.langchain4j.bean;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Data</span></span><br><span class="line"><span class="meta">@AllArgsConstructor</span></span><br><span class="line"><span class="meta">@NoArgsConstructor</span></span><br><span class="line"><span class="meta">@Document(&quot;chat_messages&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ChatMessages</span> &#123;</span><br><span class="line">	<span class="comment">//唯一标识，映射到 MongoDB 文档的 _id 字段</span></span><br><span class="line">	<span class="meta">@Id</span></span><br><span class="line">	<span class="keyword">private</span> ObjectId id;</span><br><span class="line">	</span><br><span class="line">	<span class="keyword">private</span> <span class="type">int</span> messageId;</span><br><span class="line">	</span><br><span class="line">	<span class="comment">//存储当前聊天记录列表的json字符串</span></span><br><span class="line">	<span class="keyword">private</span> String content;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="3-2、创建持久化类"><a href="#3-2、创建持久化类" class="headerlink" title="3.2、创建持久化类"></a>3.2、创建持久化类</h4><p>创建一个类实现ChatMemoryStore接口</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.wwj.java.ai.langchain4j.store;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.wwj.java.ai.langchain4j.bean.ChatMessages;</span><br><span class="line"><span class="keyword">import</span> dev.langchain4j.data.message.ChatMessage;</span><br><span class="line"><span class="keyword">import</span> dev.langchain4j.data.message.ChatMessageDeserializer;</span><br><span class="line"><span class="keyword">import</span> dev.langchain4j.data.message.ChatMessageSerializer;</span><br><span class="line"><span class="keyword">import</span> dev.langchain4j.store.memory.chat.ChatMemoryStore;</span><br><span class="line"><span class="keyword">import</span> org.springframework.beans.factory.annotation.Autowired;</span><br><span class="line"><span class="keyword">import</span> org.springframework.data.mongodb.core.MongoTemplate;</span><br><span class="line"><span class="keyword">import</span> org.springframework.data.mongodb.core.query.Criteria;</span><br><span class="line"><span class="keyword">import</span> org.springframework.data.mongodb.core.query.Query;</span><br><span class="line"><span class="keyword">import</span> org.springframework.data.mongodb.core.query.Update;</span><br><span class="line"><span class="keyword">import</span> org.springframework.stereotype.Component;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.LinkedList;</span><br><span class="line"><span class="keyword">import</span> java.util.List;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">MongoChatMemoryStore</span> <span class="keyword">implements</span> <span class="title class_">ChatMemoryStore</span> &#123;</span><br><span class="line">	<span class="meta">@Autowired</span></span><br><span class="line">	<span class="keyword">private</span> MongoTemplate mongoTemplate;</span><br><span class="line">	</span><br><span class="line">	<span class="meta">@Override</span></span><br><span class="line">	<span class="keyword">public</span> List&lt;ChatMessage&gt; <span class="title function_">getMessages</span><span class="params">(Object memoryId)</span> &#123;</span><br><span class="line">		<span class="type">Criteria</span> <span class="variable">criteria</span> <span class="operator">=</span> Criteria.where(<span class="string">&quot;memoryId&quot;</span>).is(memoryId);</span><br><span class="line">		<span class="type">Query</span> <span class="variable">query</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Query</span>(criteria);</span><br><span class="line">		<span class="type">ChatMessages</span> <span class="variable">chatMessages</span> <span class="operator">=</span> mongoTemplate.findOne(query, ChatMessages.class);</span><br><span class="line">		<span class="keyword">if</span> (chatMessages == <span class="literal">null</span>) <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">LinkedList</span>&lt;&gt;();</span><br><span class="line">		<span class="keyword">return</span> ChatMessageDeserializer.messagesFromJson(chatMessages.getContent());</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	<span class="meta">@Override</span></span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">updateMessages</span><span class="params">(Object memoryId, List&lt;ChatMessage&gt; list)</span> &#123;</span><br><span class="line">		<span class="type">Criteria</span> <span class="variable">criteria</span> <span class="operator">=</span> Criteria.where(<span class="string">&quot;memoryId&quot;</span>).is(memoryId);</span><br><span class="line">		<span class="type">Query</span> <span class="variable">query</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Query</span>(criteria);</span><br><span class="line">		<span class="type">Update</span> <span class="variable">update</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Update</span>();</span><br><span class="line">		update.set(<span class="string">&quot;content&quot;</span>, ChatMessageSerializer.messagesToJson(list));</span><br><span class="line">		<span class="comment">// 修改或新增</span></span><br><span class="line">		mongoTemplate.upsert(query, update, ChatMessages.class);</span><br><span class="line">	</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	<span class="meta">@Override</span></span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">deleteMessages</span><span class="params">(Object memoryId)</span> &#123;</span><br><span class="line">		<span class="type">Criteria</span> <span class="variable">criteria</span> <span class="operator">=</span> Criteria.where(<span class="string">&quot;memoryId&quot;</span>).is(memoryId);</span><br><span class="line">		<span class="type">Query</span> <span class="variable">query</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Query</span>(criteria);</span><br><span class="line">		mongoTemplate.remove(query, ChatMessages.class);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在<code>SeparateChatAssistantConfig</code>中，添加<code>MongoChatMemoryStore</code>对象的配置</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.wwj.java.ai.langchain4j.config;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.wwj.java.ai.langchain4j.store.MongoChatMemoryStore;</span><br><span class="line"><span class="keyword">import</span> dev.langchain4j.memory.chat.ChatMemoryProvider;</span><br><span class="line"><span class="keyword">import</span> dev.langchain4j.memory.chat.MessageWindowChatMemory;</span><br><span class="line"><span class="keyword">import</span> org.springframework.beans.factory.annotation.Autowired;</span><br><span class="line"><span class="keyword">import</span> org.springframework.context.annotation.Bean;</span><br><span class="line"><span class="keyword">import</span> org.springframework.context.annotation.Configuration;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ChatMemoryProviderConfig</span> &#123;</span><br><span class="line">	</span><br><span class="line">	<span class="comment">// 注入持久化对象</span></span><br><span class="line">	<span class="meta">@Autowired</span></span><br><span class="line">	<span class="keyword">private</span> MongoChatMemoryStore mongoChatMemoryStore;</span><br><span class="line">	</span><br><span class="line">	<span class="meta">@Bean</span></span><br><span class="line">	<span class="keyword">public</span> ChatMemoryProvider <span class="title function_">chatMemoryProvider</span><span class="params">()</span> &#123;</span><br><span class="line">		<span class="keyword">return</span> memoryId -&gt; MessageWindowChatMemory</span><br><span class="line">				.builder()</span><br><span class="line">				.id(memoryId)</span><br><span class="line">				.maxMessages(<span class="number">10</span>)</span><br><span class="line"><span class="comment">//				.chatMemoryStore(new InMemoryChatMemoryStore())</span></span><br><span class="line">				.chatMemoryStore(mongoChatMemoryStore)</span><br><span class="line">				.build();</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="4、测试"><a href="#4、测试" class="headerlink" title="4、测试"></a>4、测试</h3><p>发现MongoDB中已经存储了会话记录</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="punctuation">[</span></span><br><span class="line">  <span class="punctuation">&#123;</span></span><br><span class="line">    <span class="attr">&quot;_id&quot;</span><span class="punctuation">:</span> <span class="punctuation">&#123;</span><span class="attr">&quot;$oid&quot;</span><span class="punctuation">:</span> <span class="string">&quot;680f2346b055f44aa7fbcd22&quot;</span><span class="punctuation">&#125;</span><span class="punctuation">,</span></span><br><span class="line">    <span class="attr">&quot;content&quot;</span><span class="punctuation">:</span> <span class="string">&quot;[&#123;\&quot;contents\&quot;:[&#123;\&quot;text\&quot;:\&quot;我是张三\&quot;,\&quot;type\&quot;:\&quot;TEXT\&quot;&#125;],\&quot;type\&quot;:\&quot;USER\&quot;&#125;,&#123;\&quot;text\&quot;:\&quot;你好，张三！很高兴见到你。有什么我可以帮助你的吗？\&quot;,\&quot;type\&quot;:\&quot;AI\&quot;&#125;,&#123;\&quot;contents\&quot;:[&#123;\&quot;text\&quot;:\&quot;我是谁？\&quot;,\&quot;type\&quot;:\&quot;TEXT\&quot;&#125;],\&quot;type\&quot;:\&quot;USER\&quot;&#125;,&#123;\&quot;text\&quot;:\&quot;你刚才告诉我你是张三。如果你是在问其他身份相关的信息，或者有其他问题需要帮助，请告诉我更多的细节哦！\&quot;,\&quot;type\&quot;:\&quot;AI\&quot;&#125;]&quot;</span><span class="punctuation">,</span></span><br><span class="line">    <span class="attr">&quot;memoryId&quot;</span><span class="punctuation">:</span> <span class="number">1</span></span><br><span class="line">  <span class="punctuation">&#125;</span><span class="punctuation">,</span></span><br><span class="line">  <span class="punctuation">&#123;</span></span><br><span class="line">    <span class="attr">&quot;_id&quot;</span><span class="punctuation">:</span> <span class="punctuation">&#123;</span><span class="attr">&quot;$oid&quot;</span><span class="punctuation">:</span> <span class="string">&quot;680f234cb055f44aa7fbcd2f&quot;</span><span class="punctuation">&#125;</span><span class="punctuation">,</span></span><br><span class="line">    <span class="attr">&quot;content&quot;</span><span class="punctuation">:</span> <span class="string">&quot;[&#123;\&quot;contents\&quot;:[&#123;\&quot;text\&quot;:\&quot;我是谁？\&quot;,\&quot;type\&quot;:\&quot;TEXT\&quot;&#125;],\&quot;type\&quot;:\&quot;USER\&quot;&#125;,&#123;\&quot;text\&quot;:\&quot;您好！在这里，我看到的是一个使用此平台提问的用户。不过，您的具体身份信息我并不知晓，因为我被设计为尊重每一位用户的隐私。如果您是在寻找自我介绍的帮助，或者有其他相关问题想要讨论，请告诉我更多细节，我会尽力提供帮助！\&quot;,\&quot;type\&quot;:\&quot;AI\&quot;&#125;]&quot;</span><span class="punctuation">,</span></span><br><span class="line">    <span class="attr">&quot;memoryId&quot;</span><span class="punctuation">:</span> <span class="number">2</span></span><br><span class="line">  <span class="punctuation">&#125;</span></span><br><span class="line"><span class="punctuation">]</span></span><br></pre></td></tr></table></figure>

<h2 id="六、提示词-Prompt"><a href="#六、提示词-Prompt" class="headerlink" title="六、提示词 Prompt"></a>六、提示词 Prompt</h2><h3 id="1、系统提示词"><a href="#1、系统提示词" class="headerlink" title="1、系统提示词"></a>1、系统提示词</h3><p><code>@SystemMessage</code> 设定角色，塑造AI助手的专业身份，明确助手的能力范围</p>
<h4 id="1-1、配置-SystemMessage"><a href="#1-1、配置-SystemMessage" class="headerlink" title="1.1、配置@SystemMessage"></a>1.1、配置@SystemMessage</h4><p>在SeparateChatAssistant类的chat方法上添加@SystemMessage注解</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@SystemMessage(&quot;你是我的好朋友，请用东北话回答问题。&quot;)</span><span class="comment">//系统消息提示词</span></span><br><span class="line">String <span class="title function_">chat</span><span class="params">(<span class="meta">@MemoryId</span> <span class="type">int</span> memoryId, <span class="meta">@UserMessage</span> String userMessage)</span>;</span><br></pre></td></tr></table></figure>

<p> <code>@SystemMessage</code> 的内容将在后台转换为  <code>SystemMessage </code>对象，并与<code>UserMessage</code>一起发送给大语言模型（LLM）。</p>
<p>SystemMessaged的内容只会发送给大模型一次。 </p>
<p>如果你修改了SystemMessage的内容，新的SystemMessage会被发送给大模型，之前的聊天记忆会失效。</p>
<h4 id="1-2、测试"><a href="#1-2、测试" class="headerlink" title="1.2、测试"></a>1.2、测试</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.wwj.java.ai.langchain4j;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.wwj.java.ai.langchain4j.assistant.SeparateChatAssistant;</span><br><span class="line"><span class="keyword">import</span> org.junit.jupiter.api.Test;</span><br><span class="line"><span class="keyword">import</span> org.springframework.beans.factory.annotation.Autowired;</span><br><span class="line"><span class="keyword">import</span> org.springframework.boot.test.context.SpringBootTest;</span><br><span class="line"></span><br><span class="line"><span class="meta">@SpringBootTest</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">PromptTest</span> &#123;</span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> SeparateChatAssistant separateChatAssistant;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">testSystemMessage</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="type">String</span> <span class="variable">answer</span> <span class="operator">=</span> separateChatAssistant.chat(<span class="number">3</span>, <span class="string">&quot;今天几号&quot;</span>);</span><br><span class="line">        System.out.println(answer);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>哎呀，你这问我我还真不知道，你得自个儿瞅一眼手机或者日历啥的。我这儿也没法实时给你报时啊！哈哈。</p>
</blockquote>
<p>如果要显示今天的日期，我们需要在提示词中添加当前日期的占位符</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"> <span class="meta">@SystemMessage(&quot;你是我的好朋友，请用东北话回答问题。今天是&#123;&#123;current_date&#125;&#125;&quot;)</span><span class="comment">//系统消息提示词</span></span><br><span class="line">String <span class="title function_">chat</span><span class="params">(<span class="meta">@MemoryId</span> <span class="type">int</span> memoryId, <span class="meta">@UserMessage</span> String userMessage)</span>;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>哎呀，今儿个是2025年4月28号，你这记性咋跟金鱼似的呢！</p>
</blockquote>
<h4 id="1-3、从资源中加载提示模板"><a href="#1-3、从资源中加载提示模板" class="headerlink" title="1.3、从资源中加载提示模板"></a>1.3、从资源中加载提示模板</h4><p><code>@SystemMessage</code> 注解还可以从资源中加载提示模板：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@SystemMessage(fromResource = &quot;my-prompt-template.txt&quot;)</span></span><br><span class="line"> String <span class="title function_">chat</span><span class="params">(<span class="meta">@MemoryId</span> <span class="type">int</span> memoryId, <span class="meta">@UserMessage</span> String userMessage)</span>;</span><br></pre></td></tr></table></figure>

<p><strong>my-prompt-template.txt</strong> （文件放在 <code>resources</code>中）</p>
<blockquote>
<p>你是我的好朋友，请用东北话回答问题，回答问题的时候适当添加表情符号。</p>
</blockquote>
表示当前日期

<blockquote>
<p>你是我的好朋友，请用上海话回答问题，回答问题的时候适当添加表情符号。</p>
<p>今天是 。</p>
</blockquote>
<h3 id="2、用户提示词模板"><a href="#2、用户提示词模板" class="headerlink" title="2、用户提示词模板"></a>2、用户提示词模板</h3><p><strong>@UserMessage</strong>：获取用户输入提示词；<strong>用户提示词会在每次对话时携带</strong></p>
<h4 id="2-1、配置-UserMessage"><a href="#2-1、配置-UserMessage" class="headerlink" title="2.1、配置@UserMessage"></a>2.1、配置@UserMessage</h4><p>在<code>MemoryChatAssistant</code> 的 <code>chat</code> 方法中添加注解</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// &#123;&#123;it&#125;&#125;表示这里唯一的参数的占位符</span></span><br><span class="line"><span class="meta">@UserMessage(&quot;你是我的好朋友，请用上海话回答问题，并且添加一些表情符号。 &#123;&#123;it&#125;&#125;&quot;)</span></span><br><span class="line">String <span class="title function_">chat</span><span class="params">(String message)</span>;</span><br></pre></td></tr></table></figure>

<h4 id="2-2、测试"><a href="#2-2、测试" class="headerlink" title="2.2、测试"></a>2.2、测试</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Autowired</span></span><br><span class="line"><span class="keyword">private</span> MemoryChatAssistant memoryChatAssistant;</span><br><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">testUserMessage</span><span class="params">()</span> &#123;</span><br><span class="line">    <span class="type">String</span> <span class="variable">answer</span> <span class="operator">=</span> memoryChatAssistant.chat(<span class="string">&quot;我是环环&quot;</span>);</span><br><span class="line">    System.out.println(answer);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>嗨，环环！侬好呀～ 🌟 有啥事儿要问我伐？我一直拉海啊，准备帮侬～ 😊</p>
</blockquote>
<h3 id="3、指定参数名称"><a href="#3、指定参数名称" class="headerlink" title="3、指定参数名称"></a>3、指定参数名称</h3><h4 id="3-1、配置-V"><a href="#3-1、配置-V" class="headerlink" title="3.1、配置@V"></a>3.1、配置@V</h4><p><code>@V</code> 明确指定传递的参数名称</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@UserMessage(&quot;你是我的好朋友，请用上海话回答问题，并且添加一些表情符号。&#123;&#123;message&#125;&#125;&quot;)</span></span><br><span class="line"> String <span class="title function_">chat</span><span class="params">(<span class="meta">@V(&quot;message&quot;)</span> String userMessage)</span>;</span><br></pre></td></tr></table></figure>

<h4 id="3-2、多个参数的情况"><a href="#3-2、多个参数的情况" class="headerlink" title="3.2、多个参数的情况"></a>3.2、多个参数的情况</h4><p>如果有两个或两个以上的参数，我们必须要用<code>@V</code>，在 <code>SeparateChatAssistant</code> 中定义方法 <code>chat2</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@UserMessage(&quot;你是我的好朋友，请用粤语回答问题。&#123;&#123;message&#125;&#125;&quot;)</span></span><br><span class="line">String <span class="title function_">chat2</span><span class="params">(<span class="meta">@MemoryId</span> <span class="type">int</span> memoryId, <span class="meta">@V(&quot;message&quot;)</span> String userMessage)</span>;</span><br></pre></td></tr></table></figure>

<p>测试： <code>@UserMessage</code> 中的内容每次都会被和用户问题组织在一起发送给大模型</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">testV</span><span class="params">()</span> &#123;</span><br><span class="line">    <span class="type">String</span> <span class="variable">answer1</span> <span class="operator">=</span> separateChatAssistant.chat2(<span class="number">10</span>, <span class="string">&quot;我是环环&quot;</span>);</span><br><span class="line">    System.out.println(answer1);</span><br><span class="line">    <span class="type">String</span> <span class="variable">answer2</span> <span class="operator">=</span> separateChatAssistant.chat2(<span class="number">10</span>, <span class="string">&quot;我是谁&quot;</span>);</span><br><span class="line">    System.out.println(answer2);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="3-3、-SystemMessage和-V"><a href="#3-3、-SystemMessage和-V" class="headerlink" title="3.3、@SystemMessage和@V"></a>3.3、@SystemMessage和@V</h4><p>也可以将 <code>@SystemMessage</code> 和 <code>@V</code> 结合使用</p>
<p>在<code>SeparateChatAssistant</code> 中添加方法chat3</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@SystemMessage(fromResource = &quot;my-prompt-template3.txt&quot;)</span></span><br><span class="line">String <span class="title function_">chat3</span><span class="params">(</span></span><br><span class="line"><span class="params">    <span class="meta">@MemoryId</span> <span class="type">int</span> memoryId, </span></span><br><span class="line"><span class="params">    <span class="meta">@UserMessage</span> String userMessage, </span></span><br><span class="line"><span class="params">    <span class="meta">@V(&quot;username&quot;)</span> String username, </span></span><br><span class="line"><span class="params">    <span class="meta">@V(&quot;age&quot;)</span> <span class="type">int</span> age</span></span><br><span class="line"><span class="params">)</span>;</span><br></pre></td></tr></table></figure>

<p>创建提示词模板my-prompt-template3.txt，添加占位符</p>
<blockquote>
<p>你是我的好朋友，我是，我的年龄是，请用东北话回答问题，回答问题的时候适当添加表情 符号。</p>
<p> 今天是 。</p>
</blockquote>
<p>测试：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">testUserInfo</span><span class="params">()</span> &#123;</span><br><span class="line">    <span class="type">String</span> <span class="variable">answer</span> <span class="operator">=</span> separateChatAssistant.chat3(<span class="number">1</span>, <span class="string">&quot;我是谁，我多大了&quot;</span>, <span class="string">&quot;翠花&quot;</span>, <span class="number">18</span>);</span><br><span class="line">    System.out.println(answer);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h2 id="七、项目实战-创建硅谷小智"><a href="#七、项目实战-创建硅谷小智" class="headerlink" title="七、项目实战-创建硅谷小智"></a>七、项目实战-创建硅谷小智</h2><p>这部分我们实现硅谷小智的基本聊天功能，包含聊天记忆、聊天记忆持久化、提示词</p>
<h3 id="1、创建硅谷小智"><a href="#1、创建硅谷小智" class="headerlink" title="1、创建硅谷小智"></a>1、创建硅谷小智</h3><p>创建<code>XiaozhiAgent</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.wwj.java.ai.langchain4j.assistant;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> dev.langchain4j.service.MemoryId;</span><br><span class="line"><span class="keyword">import</span> dev.langchain4j.service.SystemMessage;</span><br><span class="line"><span class="keyword">import</span> dev.langchain4j.service.UserMessage;</span><br><span class="line"><span class="keyword">import</span> dev.langchain4j.service.spring.AiService;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> <span class="keyword">static</span> dev.langchain4j.service.spring.AiServiceWiringMode.EXPLICIT;</span><br><span class="line"></span><br><span class="line"><span class="meta">@AiService(</span></span><br><span class="line"><span class="meta">    wiringMode = EXPLICIT,</span></span><br><span class="line"><span class="meta">    chatModel = &quot;qwenChatModel&quot;,</span></span><br><span class="line"><span class="meta">    chatMemoryProvider = &quot;chatMemoryProviderXiaozhi&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">XiaozhiAgent</span> &#123;</span><br><span class="line">    <span class="meta">@SystemMessage(fromResource = &quot;zhaozhi-prompt-template.txt&quot;)</span></span><br><span class="line">    String <span class="title function_">chat</span><span class="params">(<span class="meta">@MemoryId</span> Long memoryId, <span class="meta">@UserMessage</span> String userMessage)</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="2、提示词模板"><a href="#2、提示词模板" class="headerlink" title="2、提示词模板"></a>2、提示词模板</h3><p><strong>zhaozhi-prompt-template.txt</strong></p>
<figure class="highlight markdown"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">你的名字是“硅谷小智”，你是一家名为“北京协和医院”的智能客服。</span><br><span class="line">你是一个训练有素的医疗顾问和医疗伴诊助手。</span><br><span class="line">你态度友好、礼貌且言辞简洁。</span><br><span class="line"></span><br><span class="line">1、请仅在用户发起第一次会话时，和用户打个招呼，并介绍你是谁。</span><br><span class="line"></span><br><span class="line">2、作为一个训练有素的医疗顾问：</span><br><span class="line">请基于当前临床实践和研究，针对患者提出的特定健康问题，提供详细、准确且实用的医疗建议。请同时考虑可能的病因、诊断流程、治疗方案以及预防措施，并给出在不同情境下的应对策略。对于药物治疗，请特别指明适用的药品名称、剂量和疗程。如果需要进一步的检查或就医，也请明确指示。</span><br><span class="line"></span><br><span class="line">3、作为医疗伴诊助手，你可以回答用户就医流程中的相关问题，主要包含以下功能：</span><br><span class="line">AI分导诊：根据患者的病情和就医需求，智能推荐最合适的科室。</span><br><span class="line">AI挂号助手：实现智能查询是否有挂号号源服务；实现智能预约挂号服务；实现智能取消挂号服务。</span><br><span class="line"></span><br><span class="line">4、你必须遵守的规则如下：</span><br><span class="line">在获取挂号预约详情或取消挂号预约之前，你必须确保自己知晓用户的姓名（必选）、身份证号（必选）、预约科室（必选）、预约日期（必选，格式举例：2025-04-14）、预约时间（必选，格式：上午 或 下午）、预约医生（可选）。</span><br><span class="line">当被问到其他领域的咨询时，要表示歉意并说明你无法在这方面提供帮助。</span><br><span class="line"></span><br><span class="line">5、请在回答的结果中适当包含一些轻松可爱的图标和表情。</span><br><span class="line"></span><br><span class="line">6、今天是 &#123;&#123;current<span class="emphasis">_date&#125;&#125;。</span></span><br></pre></td></tr></table></figure>

<h3 id="3、配置小智助手"><a href="#3、配置小智助手" class="headerlink" title="3、配置小智助手"></a>3、配置小智助手</h3><p>配置持久化和记忆隔离</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.wwj.java.ai.langchain4j.config;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.wwj.java.ai.langchain4j.store.MongoChatMemoryStore;</span><br><span class="line"><span class="keyword">import</span> dev.langchain4j.memory.chat.ChatMemoryProvider;</span><br><span class="line"><span class="keyword">import</span> dev.langchain4j.memory.chat.MessageWindowChatMemory;</span><br><span class="line"><span class="keyword">import</span> org.springframework.beans.factory.annotation.Autowired;</span><br><span class="line"><span class="keyword">import</span> org.springframework.context.annotation.Bean;</span><br><span class="line"><span class="keyword">import</span> org.springframework.context.annotation.Configuration;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">chatMemoryProviderXiaozhiConfig</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> MongoChatMemoryStore mongoChatMemoryStore;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="keyword">public</span> ChatMemoryProvider <span class="title function_">chatMemoryProviderXiaozhi</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> memoryId -&gt;</span><br><span class="line">            MessageWindowChatMemory.builder()</span><br><span class="line">            .id(memoryId)</span><br><span class="line">            .maxMessages(<span class="number">20</span>)</span><br><span class="line">            .chatMemoryStore(mongoChatMemoryStore)</span><br><span class="line">            .build();</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="4、封装对话对象"><a href="#4、封装对话对象" class="headerlink" title="4、封装对话对象"></a>4、封装对话对象</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.wwj.java.ai.langchain4j.bean;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> lombok.Data;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Data</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ChatForm</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> Long memoryId;<span class="comment">//对话id</span></span><br><span class="line">    <span class="keyword">private</span> String message;<span class="comment">//用户问题</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="5、添加Controller方法"><a href="#5、添加Controller方法" class="headerlink" title="5、添加Controller方法"></a>5、添加Controller方法</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.wwj.java.ai.langchain4j.controller;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.wwj.java.ai.langchain4j.assistant.XiaozhiAgent;</span><br><span class="line"><span class="keyword">import</span> com.wwj.java.ai.langchain4j.bean.ChatForm;</span><br><span class="line"><span class="keyword">import</span> io.swagger.v3.oas.annotations.Operation;</span><br><span class="line"><span class="keyword">import</span> io.swagger.v3.oas.annotations.tags.Tag;</span><br><span class="line"><span class="keyword">import</span> org.springframework.beans.factory.annotation.Autowired;</span><br><span class="line"><span class="keyword">import</span> org.springframework.web.bind.annotation.PostMapping;</span><br><span class="line"><span class="keyword">import</span> org.springframework.web.bind.annotation.RequestBody;</span><br><span class="line"><span class="keyword">import</span> org.springframework.web.bind.annotation.RequestMapping;</span><br><span class="line"><span class="keyword">import</span> org.springframework.web.bind.annotation.RestController;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Tag(name = &quot;硅谷小智&quot;)</span></span><br><span class="line"><span class="meta">@RestController</span></span><br><span class="line"><span class="meta">@RequestMapping(&quot;/xiaozhi&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">XiaozhiController</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> XiaozhiAgent xiaozhiAgent;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Operation(summary = &quot;对话&quot;)</span></span><br><span class="line">    <span class="meta">@PostMapping(&quot;/chat&quot;)</span></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">chat</span><span class="params">(<span class="meta">@RequestBody</span> ChatForm chatForm)</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> xiaozhiAgent.chat(chatForm.getMemoryId(), chatForm.getMessage());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="6、待优化"><a href="#6、待优化" class="headerlink" title="6、待优化"></a>6、待优化</h3><p>信息查询：提示词中还应该提供医院信息（如位置信息，营业时间等）、科室信息（都有哪些科室）、医生信息（都有哪些医生）</p>
<p>业务实现：预约、取消预约、查询是否预约等</p>
<p>信息查询可以使用RAG检索增强生成</p>
<p>业务实现需要通过 <strong>Function Calling</strong> 函数调用</p>
<h2 id="八、-Function-Calling-函数调用"><a href="#八、-Function-Calling-函数调用" class="headerlink" title="八、 Function Calling 函数调用"></a>八、 Function Calling 函数调用</h2><p><code>Function Calling</code> 函数调用 也叫   <code>Tools</code> 工具</p>
<h3 id="1、入门案例"><a href="#1、入门案例" class="headerlink" title="1、入门案例"></a>1、入门案例</h3><p>例如，大语言模型本身并不擅长数学运算。如果应用场景中偶尔会涉及到数学计算，我们可以为他提供 一个 “数学工具”。当我们提出问题时，大语言模型会判断是否使用某个工具。</p>
<h4 id="1-1、创建工具类"><a href="#1-1、创建工具类" class="headerlink" title="1.1、创建工具类"></a>1.1、创建工具类</h4><p>用 @Tool 注解的方法： </p>
<ul>
<li>既可以是静态的，也可以是非静态的； </li>
<li>可以具有任何可见性（公有、私有等）。</li>
</ul>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/Java/" rel="tag"># Java</a>
              <a href="/tags/LangChain4j/" rel="tag"># LangChain4j</a>
              <a href="/tags/RAG/" rel="tag"># RAG</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2025/04/20/MCP%E6%9C%8D%E5%8A%A1%E5%99%A8/" rel="prev" title="MCP服务器">
                  <i class="fa fa-angle-left"></i> MCP服务器
                </a>
            </div>
            <div class="post-nav-item">
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">

  <div class="copyright">
    &copy; 
    <span itemprop="copyrightYear">2025</span>
    <span class="with-love">
      <i class="fa fa-heart"></i>
    </span>
    <span class="author" itemprop="copyrightHolder">Phils</span>
  </div>

    </div>
  </footer>

  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>
  <div class="sidebar-dimmer"></div>
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up fa-lg"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>

</body>
</html>
